#!/bin/sh

#IFNAME=pppdrv0
#IPLOCAL=10.9.0.1
#PPPLOGNAME=root
#ORIG_UID=0
#SPEED=150
#IPREMOTE=10.9.0.14
#PPPD_PID=2021
#PWD=/
#PEERNAME=admin
#DEVICE=/dev/pts/0

CONSOLE="/dev/console"
echo "$0 processing" > $CONSOLE
env > $CONSOLE

ipmark="peer-ip:"
connmark="ESTABLISHED"
connection="L2TP-VPNS-PSK"
tunnel_file="/tmp/tunnel-ppp-${PPPD_PID}"

. /lib/functions.sh


for i in $(seq 3); do
	if [ ! -f "$tunnel_file" ]; then
		sleep 1
		continue
	fi

	break
done

if [ ! -f "$tunnel_file" ]; then
	echo "Unable to read tunnel info!" > $CONSOLE
	exit 0
fi

config_load l2tpoveripsec
config_get encryption l2tpoveripsec encryption
echo "Encrypted" "$encryption" > $CONSOLE

if [ "$encryption" = "true" ]; then
	ip_info=$(grep "$ipmark" "$tunnel_file")
	if [ -n "$ip_info" ]; then
		ip=${ip_info##$ipmark}
	fi
	echo "$ip_info" > $CONSOLE

	ipsec_info=$(ipsec status $connection|grep $connmark|grep "$ip")
	words=${#ipsec_info}
	echo "ipsec_info:" "$ipsec_info"= ="$words"= > $CONSOLE

	#ugly
	if [ "$words" -eq 0 -o "$words" = "0" ]; then
		echo "$ip haven't got ipsec tunnel with us, disconnect" > $CONSOLE
		kill -9 $PPPD_PID
	fi
fi

rm -f "$tunnel_file"
