#!/bin/bash

IFACECFG=/tmp/iface.wdchk
ifName=""
LOG_FILE=/app/logs/shortTerm-$(date '+%Y-%m-%d').log


start_ppp0()
{
	/usr/bin/systemctl enable quectel-ppp.service
	/usr/bin/systemctl start quectel-ppp.service
}

stop_ppp0()
{
	/usr/bin/systemctl stop quectel-ppp.service
	/usr/bin/systemctl disable quectel-ppp.service
}

restart_service()
{
	#/usr/bin/systemctl restart networking.service
	/usr/bin/systemctl restart ssh_vpn.service
}

restart_iface()
{
	if [ -f "$IFACECFG" ]; then
        	stop_ppp0
		ifName=$(/usr/bin/cat "$IFACECFG")
		/usr/sbin/ifup $ifName
	fi
}

check_iface()
{
	# Verifier/Réactiver ETH1/WLAN0 et si OK arrêter PPP0 si actif
   	if [ -f "$IFACECFG" ] && [ -f /tmp/ppp0.alive ]; then
        	restart_iface
        	ifCfgName=$(/usr/bin/cat "$IFACECFG")
        	/usr/bin/sleep 2
        	/usr/bin/ping -I "${ifCfgName}" -c2 -W2 google.com
        	if [ $? -eq 0 ];
		then
        		#/usr/bin/echo "<$(date)> Watchdog: $ifCfgName iface is checked OK"
        		echo "^[[33mWARN^[[0m[$(date '+%Y-%m-%d %H:%M:%S')] Network Watchdog: Restarting "${ifCfgName}" OK" >> "${LOG_FILE}"
        		/usr/bin/rm "$IFACECFG"
        	else
        		/usr/bin/echo "<$(date)> Watchdog: $ifCfgName iface is checked NO OK"
        		/usr/sbin/ifdown "${ifCfgName}"
        		/usr/bin/touch /tmp/"${ifCfgName}".started
        	fi
	fi
}


export DEBIAN_FRONTEND=noninteractive

if [ -f "/tmp/eth1.started" ] || [ -f "/tmp/wlan0.started" ]; then
	ifFile=$(/usr/bin/basename /tmp/*.started)
	ifName=$(/usr/bin/echo "$ifFile" | /usr/bin/cut -d. -f-1 | /usr/bin/cut -d_ -f1)
	#/usr/bin/echo "$ifName"
else
	exit 0
fi

if [ "$ifName" = 'eth1' ] || [ "$ifName" = 'wlan0' ]; then
   check_iface
   /usr/bin/ping -I "${ifName}" -c2 -W2 google.com
   if [ $? -eq 0 ];
   then
   	/usr/bin/echo "<$(date)> "${ifName}" iface OK"  	
   else
	/usr/bin/echo "<$(date)> "${ifName}" NO OK"
	echo "^[[31mERRO^[[0m[$(date '+%Y-%m-%d %H:%M:%S')] Network Watchdog: "${ifName}" ERROR, activate backup PPP0 link" >> "${LOG_FILE}"
	/usr/bin/echo "${ifName}" > $IFACECFG
	/usr/sbin/ifdown "${ifName}"
	/usr/bin/touch /tmp/"${ifName}".started
	# Activation PPP0 via ifdown eth1/wlan0 en auto
	#start_ppp0
   fi
fi

exit 0

