#! /bin/sh

INTERFACE="$1"
REMOTE_IP="$2"

FAIL_COUNT=0
FAIL_LIMIT=3

while :; do
	LINK_OK=0
	if ip addr show "$INTERFACE" 2>/dev/null | grep -q UP; then
		LINK_OK=1
	fi
	if [ $LINK_OK -eq 0 ]; then
		FAIL_COUNT=$((FAIL_COUNT+1))
	else
		if [ -n "$REMOTE_IP" ]; then
			if ping -c 1 -q $REMOTE_IP >/dev/null 2>&1; then
				FAIL_COUNT=0
			else
				FAIL_COUNT=$((FAIL_COUNT+1))
				logger "$0: remote IP not pingable, FAIL_COUNT: $FAIL_COUNT"
			fi
		else
			FAIL_COUNT=0
		fi
	fi
	if [ $FAIL_COUNT -ge $FAIL_LIMIT ]; then
		/sbin/reboot -f
	fi
	sleep 60
done
