#!/bin/sh

LOG="/usr/bin/logger -t $(basename "$0")[$$] -p"

main() {

	[ -z "$12" ] && echo "Error: should not be started manually" && exit 0

	if [ -e /var/run/mwan3track-$1.pid ] ; then
		kill $(cat /var/run/mwan3track-$1.pid) &> /dev/null
		rm /var/run/mwan3track-$1.pid &> /dev/null
	fi

	echo "$$" > /var/run/mwan3track-$1.pid

	local score=$(($7+$8))
	local track_ips=$(echo $* | cut -d ' ' -f 12-99)
	local host_up_count=0
	local lost=0
	local sleep_time=0

	while true; do

		sleep_time=$6

		for track_ip in $track_ips; do
			ping -I $2 -c $4 -W $5 -s $9 -q $track_ip &> /dev/null
			if [ $? -eq 0 ]; then
				let host_up_count++
			else
				let lost++
			fi
		done

		if [ $host_up_count -lt $3 ]; then
			let score--

			if [ $score -lt $8 ]; then
				score=0
			else
				sleep_time=$10
			fi

			if [ $score -eq $8 ]; then
				$LOG notice "Interface $1 ($2) is offline"
				env -i ACTION=ifdown INTERFACE=$1 DEVICE=$2 /sbin/hotplug-call iface
				score=0
			fi
		else
			if [ $score -lt $(($7+$8)) ] && [ $lost -gt 0 ]; then
				$LOG info "Lost $(($lost*$4)) ping(s) on interface $1 ($2)"
			fi

			let score++
			lost=0

			if [ $score -gt $8 ]; then
				score=$(($7+$8))
			elif [ $score -le $8 ]; then
				sleep_time=$11
			fi

			if [ $score -eq $8 ]; then
				$LOG notice "Interface $1 ($2) is online"
				env -i ACTION=ifup INTERFACE=$1 DEVICE=$2 /sbin/hotplug-call iface
				rm /var/run/mwan3track-$1.pid
				exit 0
			fi
		fi

		host_up_count=0
		sleep $sleep_time
	done
}

main "$@"
