#!/bin/bash

# return codes:
# 0 : everything ok, ppp is running, online
# 1 : error
# 2 : everything ok, ppp is not running, try to (re)connect (ifup-ppp running)
# 3 : everything ok, ppp is NOT running, offline

# 4 : everything ok, ppp is running, disconnect phase (ip-down running)
# 5 : everything ok, ppp is running, connect phase    (ip-up running)

# Bring up/down ppp

PIDFILE=/var/run/ppp-ppp_client.pid
SERVICE=ppp-client

. /etc/sysconfig/rc.conf
. /etc/sysconfig/network.conf
. /bin/network-functions

do_status ()
{
	if [ -r "$PIDFILE" ] ; then
		PID=$(/bin/cat $PIDFILE)

		# Check if still running
		/bin/kill -0 $PID > /dev/null 2>&1
		if [ "$?" != "0" ] ; then
			echo "$0: PPPD is in an undefined state. PID file exists but no corresponding process."
			echo "$0: Cleaning PID file."
			rm -f $PIDFILE
			return 1
		fi

		if [ -f /var/run/ip-down ] ; then
			echo "$0: PPPD is running but disconnecting"
			return 4
		fi

		if [ -f /var/run/ip-up ] ; then
			echo "$0: PPPD is running but still connecting"
			return 5
		fi

		if ! addr -i ppp0 ; then
			echo "$0: PPPD is running but still connecting"
			return 5
		fi

		echo "$0: PPPD is up and running"
	else
		if [ -f /var/run/if-up.pid ] ; then
			PID=$(/bin/cat /var/run/if-up.pid)

			# Check if still running
			/bin/kill -0 $PID > /dev/null 2>&1
			if [ "$?" != "0" ] ; then
				echo "$0: PPPD is in an undefined state. PID file exists but no corresponding process."
				echo "$0: Cleaning PID file."
				rm -f /var/run/if-up.pid
				return 1
			fi

			if [ -f /var/run/ip-down ] ; then
				echo "$0: PPPD is running but disconnecting"
				return 4
			fi

			if [ -f /var/run/ip-up ] ; then
				echo "$0: PPPD is running but still connecting"
				return 5
			fi

			echo "$0: PPPD is running but not online. (trying to connect)"
			return 2
		else
			echo "$0: PPPD is not up"
			return 3
		fi
	fi

	return 0
}

do_start ()
{
	/etc/init.d/softdogd wait
	ln -sf /etc/ppp-client /var/run/ppp-config

	/bin/setsid /bin/ifup-ppp > /dev/null 2>&1 &

	return
}

do_stop ()
{
	/etc/init.d/softdogd wait
	/bin/ifdown-ppp > /dev/null 2>&1

	do_status
	while [ "$?" != "3" ] ; do
		/bin/sleep 2
		do_status
	done

	return
}

case "$1" in
	start)
		do_start
		;;
	stop)
		do_stop
		;;
	status)
		do_status
		;;
	restart)
		do_stop
		do_start
		;;
	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 1
esac

exit $?
