#!/bin/sh

echo "$$" > /var/run/ip-down
LOGGER="/bin/logger -t $0"
PIDFILE=/var/run/ppp-ppp_client.pid

$LOGGER "Start"

# check if ip-up script is still running

while [ -r /var/run/ip-up ] ; do
	$LOGGER ip-up still running - delayed
	/bin/sleep 2
done

. /etc/sysconfig/rc.conf

# save parameters

INTERFACE_NAME=$1
TTY_DEVICE=$2
SPEED=$3
LOCAL_IP_ADDRESS=$4
REMOTE_IP_ADDRESS=$5
IPPARAM=$6

if [ -f /var/run/keepalive.pid ] ; then
	PID=$(/bin/cat /var/run/keepalive.pid)
	/bin/kill $PID > /dev/null 2> /dev/null
	/bin/rm -rf /var/run/keepalive.pid
fi

/bin/rm -f /tmp/ppp-connection

if [ -f /var/run/dynforward.conf.ppp ] ; then
	/bin/rm -f /var/run/dynforward.conf.ppp
fi


if [ -e "/etc/image_features" ] ; then
    . /etc/image_features
fi

if [ -e "/tmp/featurestatus.conf" ] ; then
	. /tmp/featurestatus.conf
fi

# remove default route.. but set the remembered - if any

/bin/ip route del default
if [ -f /tmp/ppp-rembered-default-route ] ; then
	$LOGGER "restoring old default route: /bin/ip route add $(/bin/cat /tmp/ppp-rembered-default-route)"
	/bin/ip route add $(/bin/cat /tmp/ppp-rembered-default-route)
	rm -f /tmp/ppp-rembered-default-route
fi

#
# configure named
#

$LOGGER "Restarting named:"
if [ "$START_NAMED" != "true" ] ; then
	$LOGGER "  skipped"
else
	/etc/init.d/named restart && $LOGGER "  done"  || $LOGGER "  failed"
fi

#
# configure ntp
#

$LOGGER "Stopping ntp:"
if [ "$START_NTP" != "true" ] ; then
	$LOGGER "  skipped"
else
	/etc/init.d/ntp stop && $LOGGER "  done"  || $LOGGER "  failed"
fi

#
# configure ipsec
#

$LOGGER "Stopping ipsec:"
if [ "$SEC_START_VPN" = "true" ] && [ "$FEATURE_VPN" = "1" ] ; then
	if [ "$START_IPSEC" != "true" ] ; then
		$LOGGER "  skipped"
	else
		/etc/init.d/ipsec stop && $LOGGER "  done" || $LOGGER "  failed"
	fi

	#
	# configure PPTP/L2TP Daemon
	#
        ipDownCheck
        $LOGGER "Stopping PPTP/L2TP Daemon:"
        if [ "$START_VPND" = "false" ]
        then
		$LOGGER "  skipped"
        else
		/etc/init.d/vpnd stop && $LOGGER "  done" || $LOGGER "  failed"
	fi
else
    $LOGGER "skipped (feature disabled or not existant)"
fi

#
# configure dyndns
#

$LOGGER "Stopping dyndns:"
if [ "$START_DYNDNS" != "true" ] ; then
	echo "skipped"
else
	/etc/init.d/dyndnsd stop > /dev/null  && echo "done" || echo "failed"
fi

#
# remove routes via dynamic interface
#

/bin/addroute -b -S allWAN > /dev/null 2>&1
/bin/addroute -b -P allWAN > /dev/null 2>&1


# toggle debug mode
if [ -r "$PIDFILE".last ] ; then
	PID=$(/bin/cat $PIDFILE.last)
	# get current debug state
	. /tmp/ppp-debug

	if [ "$DEBUG" = "false" ] ; then
		# switch on debug mode
		/bin/kill -10 $PID > /dev/null 2>&1

		# remember new state
		echo "DEBUG=true" > /tmp/ppp-debug
	fi

	/bin/rm -f "$PIDFILE".last
fi

/bin/raise_event -a PPP -n "link down" > /dev/null 2>&1

rm -f /var/run/ip-down

$LOGGER "End"

exit 0

