#!/bin/sh
#* VPNGATEWAY             -- vpn gateway address (always present)
#* TUNDEV                 -- tunnel device (always present)
#* INTERNAL_IP4_ADDRESS   -- address (always present)
#* INTERNAL_IP4_NETMASK   -- netmask (often unset)
#* INTERNAL_IP4_DNS       -- list of dns serverss
#* INTERNAL_IP4_NBNS      -- list of wins servers
#* CISCO_DEF_DOMAIN       -- default domain name
#* CISCO_BANNER           -- banner from server

fix_ip_get_output () {
	sed 's/cache//;s/metric[0-9]\+ [0-9]\+//g' | xargs echo
}

defr=/var/run/vpnc/defaultroute
gateway=/var/run/vpnc/gateway
pid=/var/run/vpnc/pid

if [ -z "$VPNGATEWAY" ]; then
	for i in "$(dirname $0)/vpnc" /usr/local/sbin/vpnc /usr/sbin/vpnc ; do
		if [ -x "$i" ]; then
			break
		fi
	done
	if [ -x "$i" ]; then
		VPNC="$i"
	else
		echo No vpnc daemon found, aborting...
		exit 1
	fi
	
	for i in "$gateway" "$defr" "$pid"; do
		mkdir -p $(dirname "$i")
	done
	
	PID="$(cat "$pid" 2> /dev/null)"
	
	if [ "$PID" ]; then
		if kill -0 "$PID" > /dev/null 2>&1; then
			echo "vpnc found running (pid: $PID, pidfile: $pid)"
			exit 1
		fi
	fi
	
	exec "$VPNC" --pid-file "$pid" --script "$0" "$@" || exit 1
fi

# started from vpnc..

ifconfig $TUNDEV inet $INTERNAL_IP4_ADDRESS \
	pointopoint $INTERNAL_IP4_ADDRESS \
	netmask 255.255.255.255 mtu 1412 up
ip route add $(ip route get $VPNGATEWAY | fix_ip_get_output)
ip route | grep '^default' | fix_ip_get_output > "$defr"
echo "$VPNGATEWAY" > "$gateway"
ip route del default
ip route add default dev $TUNDEV
ip route flush cache
exit 0
