#! /bin/bash
# User modify-able parameters 
ln_sleep=10			# How long sleep between two cycles
debug=1				# 0=silent; 1=only errors; 1=all debug messages

# Basic initialization
ln_dev_down=0			# Reboot after of # cycles, when device is down
lc_wlan_pth="/proc/net/hostap/"	# Path to HostAP process
lc_wlan_debug="/debug"		# Name of HostAP debug file
ln_if_total=0			# No of watching interfaces


declare -a lc_if_name ln_dev_down

# Settin speed of serial port
/bin/stty -F /dev/ttyS1 4800

# read configuration file
while read LINE
do
    lc_line=`echo "$LINE" | grep -E "interface" | sed 's/interface //g'`
    if [ "$lc_line" ]
    then
	(( ln_if_total += 1 ))
	lc_if_name[ln_if_total]=$lc_line
    fi
done < /etc/watchdog.opts

# Inifinitie loop
if [ "$debug" = "2" ]; then echo "Runnig script for watchdog..."; fi 
while true
do
    ln_if_index=0
    ln_alldev_running=1
    until [ $ln_if_index -ge $ln_if_total ]; do
	(( ln_if_index += 1 ))
	lc_path="$lc_wlan_pth${lc_if_name[$ln_if_index]}$lc_wlan_debug"	
	ln_dev_running=` cat $lc_path  | grep -E "dev_enabled" | sed 's/dev_enabled=//g'`
        if [ "$ln_dev_running" = "0" ]
	then
	    (( ln_dev_down[$ln_if_index] += 1 ))
	    ln_alldev_running=0
	    if [ "${ln_dev_down[$ln_if_index]}" -ge 2 ]
	    then
		logger -p local7.warning -t WATCHDOG Device ${lc_if_name[$ln_if_index]} is down, invoke SW reset ...
		iwpriv ${lc_if_name[$ln_if_index]} reset 0
	    fi
	    if [ "${ln_dev_down[$ln_if_index]}" = "4" ]
	    then
		logger -p local7.warning -t WATCHDOG Device ${lc_if_name[$ln_if_index]} is disabled, initializing reboot of system...
		echo wdt180s > /dev/ttyS1
	    	sleep 1
	    	/sbin/reboot
		exit
	    fi	
	else
	    ln_dev_down[$ln_if_index]=0
	    if [ "$debug" = "2" ]; then echo "Device ${lc_if_name[$ln_if_index]} is up."; fi
	fi	
    done
    if [ "$ln_alldev_running" = "1" ]
    then
	echo wdt130s > /dev/ttyS1
    fi  
    sleep $ln_sleep
done
