#!/bin/sh

defr=/var/lib/vpnc/defaultroute
gateway=/var/lib/vpnc/gateway
dns=/var/lib/vpnc/resolv.conf
pid=/var/lib/vpnc/pid

if [ -z "$VPNC_END" ]; then

	if [ $# -ne 0 ]; then
		echo "Usage: $0" 1>&2
		exit 1
	fi

	PID="$(cat "$pid" 2> /dev/null)"

	if [ -z "$PID" ]; then
		echo "no vpnc found running"
		exit 1
	fi

	if ! kill -0 "$PID" > /dev/null 2>&1; then
		echo "no vpnc found running"
		exit 1
	fi

	echo "Terminating vpnc daemon (pid: $PID)"
	kill -s HUP $PID
fi

# this still sucks. Invent something to sync route removal/addition with
# vpnc-connect

if [ -s "$defr" ]; then
	ip route del default > /dev/null 2>&1
	ip route add $(cat "$defr")
	test -r "$gateway" && ip route del $(cat "$gateway")
	ip route flush cache
fi

rm -f -- "$defr" "$pid" "$gateway"

# Update DNS
if [ -f $dns ] ; then
    mv -f $dns /etc/resolv.conf
fi

exit 0

