#!/bin/sh
# ../scripts/pptp-start.  Generated from pptp-start.in by configure.
#***********************************************************************
#
# pptp-start
#
# Shell script to bring up a PPTP connection
#
# Copyright (C) 2000 Roaring Penguin Software Inc.
#
# $Id: pptp-start.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-start [config_file]
#        pptp-start interface user [config_file]
# Second form overrides USER and ETH from config file.
# If config_file is omitted, defaults to /etc/ppp/pptp.conf
#
#***********************************************************************

# From AUTOCONF
#prefix=/home/zoo/pptp/
prefix=/
exec_prefix=${prefix}

# Paths to programs
CONNECT=${exec_prefix}/sbin/pptp-connect
ECHO=/bin/echo
IFCONFIG=/sbin/ifconfig

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

# Defaults
CONFIG=/etc/ppp/pptp.conf
USER=""
ETH=""
ME=`basename $0`
# Must be root
if [ "`/usr/bin/id -u`" != 0 ] ; then
    $ECHO "$ME: You must be root to run this script" >& 2
    exit 1
fi

# No Debugging
    DEBUG=""

# Sort out command-line arguments
case "$#" in
    1)
	CONFIG="$1"
	;;
    3)
	CONFIG="$3"
	;;
esac

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

# Check for command-line overriding of ETH and USER
case "$#" in
    2|3)
	ETH="$1"
	USER="$2"
	;;
esac

# 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: There already seems to be a PPTP connection up (PID $PID)" >& 2
	exit 1
    fi
    # Delete bogus PIDFILE
    rm -f "$PIDFILE" "$PIDFILE.pppd" "$PIDFILE.pptp" "$PIDFILE.start"
fi

echo $$ > $PIDFILE.start

# Start the connection in the background unless we're debugging
if [ "$DEBUG" != "" ] ; then
    $CONNECT "$@"
    exit 0
fi

$CONNECT "$@" > /dev/null 2>&1 &
CONNECT_PID=$!

if [ "$CONNECT_TIMEOUT" = "" -o "$CONNECT_TIMEOUT" = 0 ] ; then
    exit 0
fi

# Don't monitor connection if dial-on-demand
if [ "$DEMAND" != "" -a "$DEMAND" != "no" ] ; then
    exit 0
fi

# Monitor connection
TIME=0
while [ true ] ; do
    ${exec_prefix}/sbin/pptp-status $CONFIG > /dev/null 2>&1

    # Looks like the interface came up
    if [ $? = 0 ] ; then
	# Print newline if standard input is a TTY
	tty -s && $ECHO " Connected!"
	exit 0
    fi

    if test -n "$FORCEPING" ; then
	printf "%s" "$FORCEPING"
    else
	tty -s && printf "%s" "$PING"
    fi
    sleep $CONNECT_POLL
    #TIME=`expr $TIME + $CONNECT_POLL`
    #if [ $TIME -gt $CONNECT_TIMEOUT ] ; then
	#break
    #fi
done

$ECHO "TIMED OUT" >& 2
# Timed out!  Kill the pptp-connect process and quit
kill $CONNECT_PID > /dev/null 2>&1

# Clean up PIDFILE(s)
rm -f "$PIDFILE" "$PIDFILE.pppd" "$PIDFILE.pptp" "$PIDFILE.start"

exit 1

