#!/bin/sh
. /etc/functions.sh
pppX="$1"
tty="$2"
speed="$3"
local_ip="$4"
remote_ip="$5"
iface="$6"
dns1="$7"
dns2="$8"
dialin_username="$9"
din_ack="$10"
UCI_CONFIG=pptp_l2l_din
IPTABLES_CHAIN=PPTP_L2L_RULE
IPTABLES_MSS_CHAIN=PPTP_TCPMSS
RESOLV_CONF="/tmp/resolv.conf.auto"
GAP=1000
VPN_LAST_LOG_MAX=20
if [ "$din_ack" = "PPPOE" ]; then
	VPN_LAST_LOG="/tmp/pppoe_last_log"
else
	VPN_LAST_LOG="/tmp/vpn_last_log"
fi

rm /var/run/$pppX.dev 2>/dev/null
proto=`json get network.$iface.proto`
profile=`json get $dialin_username.profile -f /var/pptp_din_mapping`
routername=`uci get syslogd.syslogd.routername`
cvm_status=$(uci get cvmd.general.status)
[ -z "$profile" ] || {
	# delete tcp mss rule
	#TCPMSS=`json get $dialin_username.$pppX.mss`
	#/usr/sbin/iptables -t mangle -D $IPTABLES_MSS_CHAIN -p tcp --tcp-flags SYN,RST SYN -i $pppX -j TCPMSS --set-mss $TCPMSS
	#/usr/sbin/iptables -t mangle -D $IPTABLES_MSS_CHAIN -p tcp --tcp-flags SYN,RST SYN -o $pppX -j TCPMSS --set-mss $TCPMSS

	# delete json item
	json delete pptp_l2l.$dialin_username.ppp_if
	#json delete $dialin_username.$pppX


	# flush route cache
	#/usr/sbin/flush_route_cache.sh "ip-down"
	#/usr/sbin/ip route flush cache #Comment off by Vincent F. 2013/02/01
	#Following commands will clear route cache, not necessary to flush cache here.
	#1. ip route flush/replace
	#2. ip route flush/replace table
	#3. ip addr flush dev
	#4. ip link set device down
	
	#vpn syslog and mail alert for L2L
	conn_time=""
	[ -f /var/run/$pppX.stime ] && {
		stime=$(cat /var/run/$pppX.stime)
		ntime=$(date +%s)
		
		dtime=`expr $ntime - $stime`
		ss=`expr $dtime % 60`
		mm=`expr $dtime / 60 % 60`
		hh=`expr $dtime / 3600`
		
		conn_time="(total time connected : $hh hours $mm minutes $ss seconds)"
		rm /var/run/$pppX.stime 2>/dev/null
	}
	pptp_alert_date=$(date +"%Y-%m-%d %H:%M:%S")
	pptp_din_idx=$(cat /etc/config/pptp_l2l_din | grep pptp-l2l-din | grep pptp-l2l-din -n | grep $profile | awk -F":" '{print $1}')
	logger -p local1.notice "[L2L][DOWN][PPTP][@$pptp_din_idx:$profile]"
	logger -p local1.alert "[L2L][DOWN][PPTP][@$pptp_din_idx:$profile]"
	sh /sbin/SendAlert.sh "3" "[L2L/H2L][PPTP][$pptp_din_idx:$profile] from $routername is Down $pptp_alert_date $conn_time" >/dev/console
	sh /sbin/MailSendAlert.sh "3" "[L2L/H2L][PPTP][$pptp_din_idx:$profile] from $routername is Down $pptp_alert_date $conn_time" >/dev/console
	echo "$pptp_alert_date -- DropVPN() L2L PPTP : Profile Index = $pptp_din_idx, Name = $profile $conn_time" >> /tmp/vpn_mailalert
	/etc/mailtest.sh vpn &
	if [ $(sort $VPN_LAST_LOG/$profile 2>/dev/null | wc -l) -lt $VPN_LAST_LOG_MAX ]; then
		[ -d $VPN_LAST_LOG ] || mkdir $VPN_LAST_LOG
		echo "$profile DOWN $pptp_alert_date $conn_time" >> $VPN_LAST_LOG/$profile
	else
		lastnum=`expr $VPN_LAST_LOG_MAX - 1`
		tail -$lastnum $VPN_LAST_LOG/$profile > /tmp/tmp_vpn_last_log
		cat /tmp/tmp_vpn_last_log > $VPN_LAST_LOG/$profile
		echo "$profile DOWN $pptp_alert_date $conn_time" >> $VPN_LAST_LOG/$profile
	fi

	#send alert to cvm
	if [ "$cvm_status" == "enable" ]; then
		if [ -f /tmp/cvm/nextalert ]; then
			alertid=$(cat /tmp/cvm/nextalert)
			json -f /tmp/cvm/alert.json set $alertid time="$(date +"%Y-%m-%d %H:%M:%S %Z")" devicename="$profile" type="PPTP" description="$profile disconnected!"
			let "alertid++"
			echo $alertid > /tmp/cvm/nextalert
		else
			json -f /tmp/cvm/alert.json set 1 time="$(date +"%Y-%m-%d %H:%M:%S %Z")" devicename="$profile" type="PPTP" description="$profile disconnected!"
			mkdir -p /tmp/cvm
			echo 2 > /tmp/cvm/nextalert
		fi
	fi	
}

[ -z "$profile" -a -n "$dialin_username" ] && {
	pptp_alert_date=$(date +"%Y-%m-%d %H:%M:%S")
	conn_time=""
	[ -f /var/run/$pppX.stime ] && {
		stime=$(cat /var/run/$pppX.stime)
		ntime=$(date +%s)
		
		dtime=`expr $ntime - $stime`
		ss=`expr $dtime % 60`
		mm=`expr $dtime / 60 % 60`
		hh=`expr $dtime / 3600`
		
		conn_time="(total time connected : $hh hours $mm minutes $ss seconds)"
		rm /var/run/$pppX.stime 2>/dev/null
	}
	if [ "$din_ack" = "L2TP" ]; then
		pppid=$(cat /var/run/$pppX.pid.ipsec 2>/dev/null)
		if [ "$pppid" != "" ]; then
			din_ack="L2TP/IPSec"
		fi
	else
		[ -z "$din_ack" ] && din_ack="PPP"
	fi
	rm /var/run/$pppX.pid.ipsec 2>/dev/null
	logger -p local1.notice "[H2L][DOWN][$din_ack][@$dialin_username]"
	logger -p local1.alert "[H2L][DOWN][$din_ack][@$dialin_username]"
	sh /sbin/SendAlert.sh "3" "[H2L][DOWN][$din_ack][@$dialin_username] from $routername is Down $pptp_alert_date $conn_time" >/dev/console
	sh /sbin/MailSendAlert.sh "3" "[H2L][DOWN][$din_ack][@$dialin_username] from $routername is Down $pptp_alert_date $conn_time" >/dev/console
	echo "$pptp_alert_date -- DropVPN() H2L $din_ack : Name = $dialin_username $conn_time" >> /tmp/vpn_mailalert
	/etc/mailtest.sh vpn &
	if [ $(sort $VPN_LAST_LOG/$dialin_username 2>/dev/null | wc -l) -lt $VPN_LAST_LOG_MAX ]; then
		[ -d $VPN_LAST_LOG ] || mkdir $VPN_LAST_LOG
		echo "$dialin_username DOWN $pptp_alert_date $conn_time" >> $VPN_LAST_LOG/$dialin_username
	else
		lastnum=`expr $VPN_LAST_LOG_MAX - 1`
		tail -$lastnum $VPN_LAST_LOG/$dialin_username > /tmp/tmp_vpn_last_log
		cat /tmp/tmp_vpn_last_log > $VPN_LAST_LOG/$dialin_username
		echo "$dialin_username DOWN $pptp_alert_date $conn_time" >> $VPN_LAST_LOG/$dialin_username
	fi
}

proto=${proto%(*}
[ -z "$proto" ] || {
	##### remove old dns record
	logger "$iface PPP($$)ip-down: remove old dns record"
	sed -i "/#$iface$/d" $RESOLV_CONF 2> /dev/null
	[ "$proto" = "pptp" ] && {
		over_dns=`json get network.$iface.over_dns`
		for ns in $over_dns; do
			echo "nameserver $ns #$iface" >> /tmp/resolv.conf.auto
		done
	}
	ifname=`json get network.$iface.ifname`
	ipaddr=`json get network.$iface.ipaddr`
	rt_table_id=`get_route_table_id $iface`
	[ -z "$ipaddr" ] || /usr/sbin/iptables -t mangle -D OUTPUT_WAN -s $ipaddr -j MARK --set-mark $rt_table_id 2>/dev/null
	/usr/sbin/ipset -F ip_$iface
	/usr/sbin/ipset -F ipalias_$iface
	
	#clear all expired routes
	logger "$iface PPP($$)ip-down: clear all expired routes"
	/usr/sbin/ip route flush table $rt_table_id
	until [ -z `/usr/sbin/ip rule |grep $((33267+$rt_table_id))` ]
	do
		/usr/sbin/ip rule del pref $((33267+$rt_table_id))
	done
	
	if [ "$proto" = "pppoe" ]; then
		json set network.$iface ipaddr= gateway= dns=
		json -f /var/cd_status set interface.$iface ipaddr= gateway=
		#remove ip alias
		ip_alias=`json get network.$iface.ip_alias`
		[ -n "$ip_alias" -a -n "$rt_table_id" ] && {
			logger "$iface PPP($$)ip-down: remove expired ip alias related settings"
			for ip2 in $ip_alias; do
				echo $ip2 | grep "/" >/dev/null || continue
				/usr/sbin/iptables -t mangle -D OUTPUT_WAN -s $ip2 -j MARK --set-mark $rt_table_id
			done
			json delete network.$iface.ip_alias
		}
	fi
	#TOCHK: what is about proto=PPTP's alias?
	logger "$iface PPP($$)ip-down: call hotplug-call iface (ifdown)"
	env -i ACTION="ifdown" INTERFACE="$iface" DEVICE="$ifname" PROTO="$proto" /sbin/hotplug-call "iface" &
}

[ -d /etc/ppp/ip-down.d ] && {
	for SCRIPT in /etc/ppp/ip-down.d/*
	do
		[ -x "$SCRIPT" ] && "$SCRIPT" $@
	done
}

if [ "$(pidof udp-broadcast-relay)" ] 
then
  killall udp-broadcast-relay
  all_ppp=$(echo $(ifconfig | grep -o ppp[0-9]*))
  localif=$(uci -q get pptpd_config.pptpd.localif || echo 'lan1')
  nbns_off=$(uci -q get pptpd_config.pptpd.disable_nbns || echo '1')
  logger -p local1.notice "PPTP client left. Resetting UDP Broadcast Relay on port 137"
  [ -n "$all_ppp" -a "$nbns_off" == "0" ] && /usr/sbin/udp-broadcast-relay -f 1 137 lan-$localif $all_ppp
fi
