#!/bin/bash
##################################################################
#
# Title:     WiFi_Check 
# Author:    det (SmartApfel Forum)
#
Version="v.0.17"
MYSELF=${0##*/}
#
# Purpose:
#
# The script checks, in WiFi the default gateway is reachable 
# and if not WiFi will be restarted
#
# Uses a lock file which prevents the script from running more
# than one at a time.  If lockfile is old, it removes it
#
# If auto-detection returns incorrect values then manually set
# remove the Route (#) and adjust variable,
# interface = "wlan0" monitors interface wlan0 
# ToolDir = "" folder where this script resides
# Gateway = "" enter for VPN tunnel usage
#
#Interface="wlan0"
#ToolDir="$HOME/hbridge_install/files"
#Gateway="192.168.23.1"
#
# Instructions:
# o Add to crontab from user root
# o sudo su
# o crontab -e
#
# Run Every 5 mins - Seems like ever min is over kill unless
# this is a very common problem.  If once a min change */5 to *
# once every 2 mins */5 to */2 ... 
#
# */5 * * * * /usr/local/bin/WiFi_Check.sh 2>&1 | /usr/bin/logger -t WiFi_check
#
##################################################################
usage="Benutze: $MYSELF [-r|-kill|-h/?]\033[0m
 Parameters:
  -h/? - shows the help and displays the automatically determined variables	(exit -1)
  -r   - removes the system link						(exit 1)
  -kill  - kill the Process while it is still running				(exit 3)
"
##################################################################
#MYNAME=${MYSELF%.*}
# Settings
# Where and what you want to call the Lockfile
lockfile="/var/run/${MYSELF}.pid"
# Which Interface do you want to check/fix
iface="$(ip addr | awk '/state UP/ {print $2}')"
iface=${iface%:*}								# inkl ":" v.re abschneiden
iface=$(echo "${iface//[$'\t\r\n']}")			# Zeilenumbruch entfernen
[ ${iface} = "eth0:wlan0" ] && iface=eth0
[ -n "${Interface}" ] && iface=${Interface}
toolDir=$(dirname "$(readlink -e "$0")")
[ -n "${ToolDir}" ] && toolDir=${ToolDir}
##################################################################
gateway=$(/sbin/route -n | /bin/grep 'UG[ \t]' | /usr/bin/awk '{print $2}')
gateway=$(echo "${gateway}" | tr "\n" "A")		# \n durch A ersetzen
gateway=${gateway%%A*}							# von re inkl. letztem A löschen
[ "$gateway" = "" ] && gateway=${Gateway}		# fallback VPN-Tunnnel

echo -e "Starting ${MYSELF} ($Version) use iface: $iface"

[ "$1" = "-r" ] && sudo rm -fr /usr/local/bin/${MYSELF} >> /dev/null && echo "System-Link entfernt" && exit 1
[ "$1" = "-h" ] || [ "$1" = "?" ] || [ "$1" = "-?" ] && echo -e "\033[0;33m\n$usage\n\033[0;33mInfo (autom. Erkennung):\n\033[0m\t Interface=\"$iface\"\n\t Gateway=\"$gateway\"\n\t ToolDir=\"$toolDir\"\n" && exit -1
[ "$1" = "-kill" ] && kill_pid=1

if [ -f $toolDir/${MYSELF} ]; then
  [ ! -h /usr/local/bin/${MYSELF} ] && sudo ln -s $toolDir/${MYSELF} /usr/local/bin/${MYSELF} && echo "System-Link zu $toolDir/${MYSELF} wurde erstellt."
fi

# Check to see if there is a lock file
if [ -e $lockfile ]; then
    # A lockfile exists... Lets check to see if it is still valid
    pid=`cat $lockfile`
#    if /bin/kill -0 $pid &>1 > /dev/null ; then			# org.
    if ps ax | grep -v grep | grep $pid > /dev/null ; then
    	[ "${kill_pid}" -eq 1 ] && echo "Process still running - let us kill it!!!" && sudo kill "$pid" && exit 3
    	# || echo "Couldn't kill $pid"
        # Still Valid... lets let it be...
        echo "Process still running, Lockfile valid"
        exit 2
    else
        # Old Lockfile, Remove it
        echo "Old lockfile, Removing Lockfile"
        sudo /bin/rm -rf $lockfile
    fi
fi

# If we get here, set a lock file using our current PID
sudo bash -c "echo $$ > $lockfile"

# We can perform check
#echo "Performing Network check for $iface"
if /bin/ping -c2 $gateway 2>&1 > /dev/null ; then
    echo "Network is Okay"
else
    echo "ERROR Network connection down! Attempting reconnection."
    sudo /sbin/ifconfig $iface down
    /bin/sleep 5
    sudo /sbin/ifconfig $iface up
fi

echo "Current Setting:"
sudo /sbin/ifconfig $iface | grep "inet "
 
# Check is complete, Remove Lock file and exit
echo "process is complete, removing lockfile"
sudo /bin/rm -rf $lockfile

exit 0

##################################################################
# End of Script
##################################################################
