#!/bin/bash

# check if cron is still running; if it is, then just exit; otherwise execute cron job
#[[ -f /tmp/*.vpncron ]] && exit 1

# create a temp file with suffix
TEMP_FILE=`mktemp --suffix .vpncron`
touch $TEMP_FILE

EXTIF="ppp0" # external interface, may be empty
IFCONFIG=/sbin/ifconfig
AWK=/bin/awk

HOSTS="sg3.gazduire.ro vg11.gazduire.ro rg5.gazduire.ro dbv5.gazduire.ro"
# no ping request
COUNT=1

for server in $HOSTS
do
  count=$(ping -c $COUNT $server | grep 'received' | awk -F',' '{ print $2 }' | awk '{ print $1 }')
  if [ $count -eq 0 ]; then
    # 100% failed
    echo "Host : $server is down (ping failed) at $(date)"
    /etc/init.d/vpn-gzd stop
    sleep 1
    /etc/init.d/vpn-gzd start
  fi
done

# get the external IP address - it returns empty string if it is not up
if [ -n "$EXTIF" ]; then
EXTIP=`$IFCONFIG | grep inet | grep -v 127.0.0.1 | grep -v 10.208 | grep -v inet6 | $AWK '{print $2}'`
fi
#echo " External IP: $EXTIP"

if [ -z "$EXTIP" ]; then
	echo "Starting VPN tunnel.."
	/etc/init.d/vpn-gzd stop
	sleep 1
	/etc/init.d/vpn-gzd start
else
	echo "VPN tunnel is connected"
fi

# delete cron temporary file
rm -f $TEMP_FILE
