#!/bin/bash
# Copyright 2017 Lucid Networks sloeckle
# Package Version 1.11-2 - Script Version 4

. /opt/nexp-tools/nexp-tools.lib

source /etc/nexp-tools/nexp-tools.conf

PINGHOST="172.25.0.1"
systeminfo

pingcheck(){
        ping -c4 $PINGHOST
        return $?
}

tuncheck(){
	sysdate=$(date)
	tunstate=$(cat /sys/class/net/tun0/operstate)
        if [[ $tunstate == "unknown" ]]; then
	  pingcheck
	  RESULT=$?
	  case $RESULT in
	    0)
	      #ping OK, do nothing
	    ;;
	    *)
	      echo "$sysdate - Ping test failed. Restarting tunnel." >> /var/log/nexp-tools/tunnelcheck.log
	      /etc/init.d/openvpn restart
	      echo -e $systeminfo | mutt -s "$HOSTNAME Tunnelcheck Ping Test Failed. Restarting Tunnel." -a $dir/$time.png -- $SYSMAILTO
	      exit 1
	    ;;
	  esac
	else	
	  echo "$sysdate - Tunnel interface test failed. Restarting tunnel." >> /var/log/nexp-tools/tunnelcheck.log
	  /etc/init.d/openvpn restart
          echo -e $systeminfo | mutt -s "$HOSTNAME Tunnelcheck Interface Test Failed. Restarting Tunnel." -a $dir/$time.png -- $SYSMAILTO
	  exit 1
        fi
	routelist=$(netstat -rn)
        if [[ $routelist != *"172.25.0.0"* || $routelist != *"172.25.16.0"* || $routelist != *"172.30.0.0"* ]]; then
	  echo "$sysdate - Route test failed. Restarting tunnel." >> /var/log/nexp-tools/tunnelcheck.log
	  /etc/init.d/openvpn restart
	  echo -e $systeminfo | mutt -s "$HOSTNAME Tunnelcheck Route Test Failed. Restarting Tunnel." -a $dir/$time.png -- $SYSMAILTO
          exit 1
	fi
}

tuncheck
