#!/bin/sh -Cfu


set -Cfu


cd /root/files/fbsd/embedded || exit 1


host=npinc

ip=ask-m-001

url="http://$ip/"

http=1


case "$@"
in
	*no-http*) http= ;;
esac


start=0

end=0

status=up


_http()
{
	echo
	echo "trying to request $url"
	
	
	while true
	do
		fetch -T 1 -qo- "$url" 2> /dev/null
		
		
		if [ $? = 0 ]
		then
			end_http="`date +%s`"
			
			
			http_time="$(($end_http - $start))"
			all_time="$(($end_http - $start_shutdown))"
			
			echo
			echo "got http response after ~${http_time}s (since host stopped responding to pings)"
			echo
			echo "all time from shutdown ~${all_time}s"
			
			
			break
		fi
	done
}


pgrep -af "$0" | fgrep -v "$$" | xargs pkill -l


while true
do
	echo "ssh '$host' shutdown -r now"
	
	ssh "$host" 'sh -c "shutdown -r now > /dev/null 2>&1"'
	
	
	if [ $? = 0 ]
	then
		break
	else
		sleep 1
	fi
done


start_shutdown="`date +%s`"


echo
echo "pinging $host / $ip"
echo '! = up, . = down'


while true
do
	ping -q -c 1 -t 1 "$ip" > /dev/null 2>&1
	
	
	if [ $? = 0 ]
	then
		echo -n !
		
		
		if [ $status = down ]
		then
			end="`date +%s`"
			
			status=up
			
			
			reboot_time="$(($end - $start))"
			
			echo
			echo "reboot lasted ~${reboot_time}s"
			
			
			if [ "$http" ]
			then
				_http
			fi
			
			
			exit
		fi
		
		
		sleep 1
	else
		echo -n .
		
		
		if [ $status = up ]
		then
			start="`date +%s`"
			
			status=down
		fi
	fi
done
