#!/bin/sh
PATH=/sbin:/usr/sbin:/bin:/usr/bin

# Source function library.
. /etc/init.d/functions

cd /etc/sysconfig/network-scripts
. network-functions

# ifup-post for PPP is handled through /etc/ppp/ip-up

CONFIG=$1
[ -f "$CONFIG" ] || CONFIG="ifcfg-$1"
source_config

if [ -z "$PPTP_SERVER_IP" ]; then
  echo "ifup-pptp for $DEVICE exiting"
  logger -p daemon.info -t ifup-pptp \
    "PPTP-server IP address was not defined"
  exit 1
fi

if [ -z "$DISCONNECTTIMEOUT" ]; then
  DISCONNECTTIMEOUT=2
fi

if [ -z "$RETRYTIMEOUT" ]; then
  RETRYTIMEOUT=30
fi

if [ -z "$IDLETIMEOUT" ]; then
  IDLETIMEOUT=600
fi

if [ "$2" = "boot" -a "$ONBOOT" = "no" ]; then
  exit
fi
PPPD=/usr/sbin/pppd
[ -x "$PPPD" ] || {
  echo "$PPPD does not exist or is not executable"
  echo "ifup-pptp for $DEVICE exiting"
  logger -p daemon.info -t ifup-pptp \
    "$PPPD does not exist or is not executable for $DEVICE"
  exit 1
}


opts="lock"
if [ -n "$PAPNAME" ] ; then
  opts="$opts user $PAPNAME remotename $DEVNAME"
else
  (logger -p daemon.info -t ifup-pptp \
	"PAPNAME must be defined in ifcfg-$DEVNAME" &)&
  echo "PAPNAME must be defined in ifcfg-$DEVNAME"
  exit 1;
fi
if [ -n "$CALL" ]; then
	opts="$opts call $CALL"
fi
if [ "$ESCAPECHARS" != yes ] ; then
  opts="$opts asyncmap 00000000"
fi
if [ "$PEERDNS" != no ] ; then
  opts="$opts usepeerdns"
fi
if [ -n "$MRU" ] ; then
  opts="$opts mru $MRU"
fi
if [ -n "$MTU" ] ; then
  opts="$opts mtu $MTU"
fi
if [ -n "$IPADDR$REMIP" ] ; then
  # if either IP address is set, the following will work.
  opts="$opts $IPADDR:$REMIP"
fi
if [ "$DEBUG" = yes ] ; then
  opts="$opts debug"
fi
if [ "$DEMAND" = yes ]; then
    opts="$opts demand ktune idle $IDLETIMEOUT holdoff $RETRYTIMEOUT"
fi
if [ "$DEFROUTE" != no ] ; then
  # pppd will no longer delete an existing default route
  # so we have to help it out a little here.
  route del default >/dev/null 2>&1
  opts="$opts defaultroute"
fi

$PPPD $opts updetach ipparam "$DEVICE" linkname "$DEVICE" $PPPOPTIONS connect "/bin/true" pty "/usr/sbin/pptp $PPTP_SERVER_IP --nolaunchpppd $EXTRA_PPTP_OPTS" &> /dev/null
RETVAL=$?

if [ $RETVAL = 0 ]; then
  (logger -p daemon.info -t ifup-pptp \
	"PPTP tunnel to $PPTP_SERVER_IP started for $DEVICE" &)&
else
  (logger -p daemon.info -t ifup-pptp \
	"PPTP tunnel to $PPTP_SERVER_IP startup for $DEVICE failed" &)&
fi

exit $RETVAL
