#!/bin/sh

PPTPSERVER=$1
shift
ACCOUNT=$1
shift
PASSWORD=$1
shift
PPPDOPT="$*"
WAIT=4

if [ -f /etc/ppp/pap-secrets -a ! -f /etc/ppp/pap-secrets.sav ]; then
	mv /etc/ppp/pap-secrets /etc/ppp/pap-secrets.sav
fi
if [ -f /etc/ppp/chap-secrets -a ! -f /etc/ppp/chap-secrets.sav ]; then
	mv /etc/ppp/chap-secrets /etc/ppp/chap-secrets.sav
fi
echo "$ACCOUNT * $PASSWORD *" > /etc/ppp/pap-secrets
echo "$ACCOUNT * $PASSWORD *" > /etc/ppp/chap-secrets

/usr/bin/pptp ${PPTPSERVER} user ${ACCOUNT} ${PPPDOPT} || exit 1

GW=`route -n | while read line; do
	set - $line
	case "$4" in
	*G*H*|*H*G*)
		:
		;;
	*G*)
		case "$1" in
		0.0.0.0)
			echo $2
			;;
		esac
		;;
	esac
done`
set - ${GW}
GW=$1

route add -host ${PPTPSERVER} gw ${GW} || exit 1
route del -net default

PPTPADDR=`route -n | while read line; do
	set - $line
	case "$4" in
	*G*H*|*H*G*)
		case "$2" in
		"$GW")
			echo $1
			;;
		esac
		;;
	esac
done`
set - ${PPTPADDR}
PPTPADDR=$1

sleep ${WAIT}
route add -net default gw ${PPTPADDR}
