#!/bin/sh

# vi(1) se tabstop=2

# read in our configuration:
. ~/.lpingrc || exit

ostate= # old (prior) state (initially not known)
# 0 up/nominal
# 1 down / check failed
# null for unknown / not yet known

# Check
ck(){
	ping -n -c 1 "$IP" >>/dev/null
}

# sleep(1) for some bit (delay)
Sleep(){
	sleep "$sleeps"
}

tT(){
	# set t to seconds since epoch
	# set T to human readable current UTC (Z) time
	eval $(TZ=GMT0 date +"t='%s' T='%Y-%m-%dT%H:%M:%SZ'")
}

# SIGHUP to reread our config
trap '
	. ~/.lpingrc || exit
' 1

hush= # silence alert up to this (epoch) time
# SIGINT to set/extend hush:
trap '
	case "$hush" in
		"")
			hush=$(($(date +%s) + hushinc))
		;;
		*)
			hush=$((hush + hushinc))
		;;
	esac
	printf '\''%s\n'\'' \
		"hushed until $(TZ=GMT0 date +%Y-%m-%dT%H:%M:%SZ -d @$hush)"
' 2

while :
do
	if ck; then
		state=0 # up/nominal
		hush= # (re)set
		case "$ostate" in
			0)
				# remains up
				: # nothing to report/do
			;;
			*)
				# down --> up or initial up
				tT
				printf '%s\n' "$T $t UP"
			;;
		esac
	else
		state=1 # down / check failed
		case "$ostate" in
			1)
				# remains down
				tT
				s=$((t - ds)) # seconds down
				[ -z "$hush" ] || [ "$hush" -gt "$t" ] || hush= # reset expired
				if \
					[ "$s" -lt "$alerts" ] ||
					[ -n "$hush" ]
				then
					ALERT=
				else
					ALERT="$alert"
				fi
				printf '%s\n' "$ALERT$T $t DOWN ${s}s since $Ds"
			;;
			*)
				# up --> down or initial down
				tT # down since:
				ds="$t"
				Ds="$T"
				printf '%s\n' "$T $t DOWN"
			;;
		esac
	fi
	ostate="$state"
	Sleep
done
