#!/bin/bash
# vim:tabstop=4:softtabstop=0:shiftwidth=4
#
# Script to start/stop ppp-watcher
#

### BEGIN INIT INFO
# Provides:          ppp
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Watches for dead ppp0 processes and restarts them
# Description: If ppp0 adaptor is missing it wil resart pon myvpn
### END INIT INFO

####### REVISION HISTORY ########
#=.
#=>N-000	Browch	22Dec10 Initial version 
#=.

# set -e says exit on error!
#set -e


function start_dead()
{
	/sbin/ifconfig ppp0 2> /dev/null 1> /dev/null
	if [ $? -ne 0 ]; then
		# pid file left, see if other script cleans it up in 10 seconds
		#echo "restarting myvpn"
		/usr/bin/pon myvpn
	#else
		#echo "myvpn running"
	fi
}
		
# main()

case $1 in
	start)
		if [ -f /var/run/ppp-watcher.pid ]; then
			PID=`cat /var/run/ppp-watcher.pid`
			OK=`ps --no-heading p ${PID}`
			if [ "x$OK" = "x" ]; then
				rm /var/run/ppp-watcher.pid
				$0 startreally &
			else
				echo "already running"
			fi
		else
			$0 startreally &
		fi
		;;
	startreally)
		echo $$ >/var/run/ppp-watcher.pid
		while [ 0 ]; do
			start_dead
			if [ $? -ne 0 ];then
				exit 1
			fi
			sleep 60
		done
		;;
	stop)
		if [ -f /var/run/ppp-watcher.pid ]; then
			kill `cat /var/run/ppp-watcher.pid`
			rm /var/run/ppp-watcher.pid
		fi
		;;
	*)
		echo "Usage: $0 start|stop"
		;;
esac
exit 0


