#!/bin/sh
# ../scripts/pptp-stop.  Generated from pptp-stop.in by configure.
#***********************************************************************
#
# pptp-stop
#
# Shell script to bring down a PPTP connection
#
# Copyright (C) 2000 Roaring Penguin Software Inc.
#
# $Id: pptp-stop.in,v 1.2 2005/08/10 00:25:19 dfs Exp $
#
# This file may be distributed under the terms of the GNU General
# Public License.
#
# LIC: GPL
#
# Usage: pptp-stop [config_file]
# If config_file is omitted, defaults to /etc/ppp/pptp.conf
#
#***********************************************************************

# Set to "C" locale so we can parse messages from commands
LANG=C
export LANG

ME="`basename $0`"
LOGGER="/usr/bin/logger -t $ME"
CONFIG="$1"
if [ "$CONFIG" = "" ] ; then
    CONFIG=/etc/ppp/pptp.conf
fi

if [ ! -f "$CONFIG" -o ! -r "$CONFIG" ] ; then
    echo "$ME: Cannot read configuration file '$CONFIG'" >& 2
    exit 1
fi
export CONFIG
. $CONFIG

PPTP_PIDFILE="$PIDFILE.pptp"
PPPD_PIDFILE="$PIDFILE.pppd"
STARTPID="$PIDFILE.start"

# Backward config file compatibility
if test "$DEMAND" = "" ; then
	DEMAND=no
fi

# Ignore SIGTERM
trap "" 15

# Check for pidfile
if [ -r "$PIDFILE" ] ; then
    PID=`cat $PIDFILE`

    # Check if still running
    kill -0 $PID > /dev/null 2>&1
    if [ $? != 0 ] ; then
	echo "$ME: The pptp-connect script (PID $PID) appears to have died" >& 2
    fi

while [ true ] ; do
	echo "pptp_procid pptp $PPTP_PIDFILE"
	pptp_procid pptp $PPTP_PIDFILE
    if [ "$?" != 0 ] ; then
	break
    fi
    # Kill pptp, which should in turn kill pptp
    if [ -r "$PPTP_PIDFILE" ] ; then
	PPTP_PID=`cat "$PPTP_PIDFILE"`
	$LOGGER -p daemon.notice "Killing pptp"
	echo "Killing pptp ($PPTP_PID)"
	kill -9 $PPTP_PID > /dev/null 2>&1
    fi
    sleep 1
done

    # Kill pppd, which should in turn kill pptp
#    if [ -r "$PPPD_PIDFILE" ] ; then
#	PPPD_PID=`cat "$PPPD_PIDFILE"`
#	$LOGGER -p daemon.notice "Killing pppd"
#	echo "Killing pppd ($PPPD_PID) in $PPPD_PIDFILE"
#	kill $PPPD_PID > /dev/null 2>&1
#    fi

    # Kill pptp-start
    PIDS=`cat $STARTPID`
    kill -0 $PIDS > /dev/null 2>&1
    if [ $? = 0 ] ; then
	$LOGGER -p daemon.notice "Killing pptp-connect"
	kill $PIDS > /dev/null 2>&1
    fi

    # Kill pptp-connect
    $LOGGER -p daemon.notice "Killing pptp-connect"
    echo "Killing pptp-connect ($PID)"
    kill -9 $PID > /dev/null 2>&1

    # Kill pppd again, in case it's still hanging around
    if [ -r "$PPPD_PIDFILE" ] ; then
	PPPD_PID=`cat "$PPPD_PIDFILE"`
	kill $PPPD_PID > /dev/null 2>&1
	sleep 1
	kill -9 $PPPD_PID > /dev/null 2>&1
    fi

    rm -f "$PIDFILE" "$PPPD_PIDFILE" "$PPTP_PIDFILE" "$STARTPID"
else
    echo "$ME: No PPTP connection appears to be running" >&2
    exit 1
fi

exit 0
