#!/bin/sh

# This script have to be called by cron, not very often: say, once per 10 minutes.

. /etc/rc.subr
. /opt/etc/globals

$touch $logfile

# echo "`$DATECMD` : nothing" >> $logfile

if !($ping -c 2 $good_host > /dev/null 2>&1) ; then
	echo "`date +\"%Y-%m(%b)-%d(%a), %Hh:%Mm:%Ss\"`: $good_host unreachable; re-establishing connection..." | $tee -a $logfile
	if [ -f $lockfile ] ; then
		echo "`date +\"%Y-%m(%b)-%d(%a), %Hh:%Mm:%Ss\"`: recursive call of $0" | $tee -a $logfile
		exit
	fi
	$touch $lockfile
	count=1
	trap break SIGINT
	while !($ping -c 2 $good_host > /dev/null 2>&1); do
		echo "$0 (count: ${count}): Network is still down !"
.		$try_uplink
		$sleep $((count*2))
		count=$((count+1))
	done
	$rm $lockfile
	# Reload firewall rules
	/opt/etc/multihomed.sh
	# Restart dependent daemons:
	# - openvpn:
	/opt/etc/openvpn/restart-instances
	# - pptp server:
	/opt/etc/pptpsrv/restart
	# - transmission
	# /usr/local/etc/rc.d/transmission onerestart
else
	# We are online. Check state of network daemons
	/opt/etc/openvpn/check-instances
	/opt/etc/pptpsrv/check
	# TODO: check other ones started by rc scripts
fi

# HDD monitoring. This is quite time-consuming, thus shouldn't be
# initiated once per minute, as for power & other temperatures.
/opt/etc/hddmon.sh

# ZFS pool monitoring
/opt/etc/zpmon.sh

# Update predefined ipfw table(s) (currently, BADNETS_TID)
/opt/etc/update-tables.sh

# Power conditions will be monitored every minute in separate script.

# FIXME
# /etc/rc.d/ldconfig start
# . /opt/etc/reload-netservers

