#!/bin/sh

. /usr/bin/scriptlib

ETH=`rdcsman 0x8000F231 str`
L2TP_RESULT_FILE="/var/run/l2tp-result"
PIDFILE_PPPD="/var/run/ppp-l2tp.pid"
RESOLV_CONF="/etc/resolv.conf"
L2TP_LNSSERVER=`rdcsman 0x00060600 str`
L2TP_LNSPORT=1701
PORTSCAN="/usr/bin/port-scan"
PORTSCAN_RESULT="/var/run/pscan-result"   

#read connect flag here, to avoid udhcp-start script change it.
CNT_FORCE=`rdcsman 0x8001000E u16`

l2tp_status()
{
	if [ -r $PIDFILE_PPPD ] ; then
		sl_get_ppp_PID_IFname $PIDFILE_PPPD PPP_PID PPP_IF
		if [ $? = 0 ] ; then		
		    # check the cnt status is CONNECT 
			CNTSTATUS=`rdcsman 0x80060700 u16`
			if [ $CNTSTATUS != 2 ] ; then
				echo "CNTSTATUS=$CNTSTATUS"
				return 1
			fi	
			logger -t "l2tp" "Link is up and running on interface $PPP_IF (PID: $PPP_PID)"
			echo "l2tp-status: Link is up and running on interface $PPP_IF"
            return 0
    	fi
	fi 		
	return 1	
}

test_lns_exist()
{
    logger -t "l2tp" "Try to ping L2TP Server ! Wait for reply ..." 
    echo "Try to ping L2TP Server ! Wait for reply ..." 
    
    # Try 3 Times
    for i in 1 2 3
    do
        got=0
        CFG=`ping -c1 $L2TP_LNSSERVER`
        if [ $? = 0 ] ; then
            stt=0
            for s in $CFG
            do
                if [ $stt = 1 ] ; then
                    L2TP_LNSSERVER=${s%:*}
                    # write back L2TP Server IP address.
                    wrcsman "0x80060010 \"$L2TP_LNSSERVER"
                    got=1
                    break		 
                fi
            
                if [ $s = "from" ] ; then
                    stt=1
                fi	   
            done
        fi
        
        [ $got = 1 ] && break
        sleep 1
    done

    if [ $got = 0 ] ; then	
        echo "Ping packet can't reach the L2TP Server !" 
        logger -t "l2tp" "Ping packet can't reach the L2TP Server !" 
        logger -t "l2tp" "May the packet drop by the server's firewall or your router behind the firewall !?"
        exit 1 
    fi  
}

test_lns_port()
{
    local timeout=5
    local idx=0
    
    logger -t "l2tp" "Send detect packet to L2TP Server ! Wait for reply ..." 
    echo "Send detect packet to L2TP Server ! Wait for reply ..." 
    $PORTSCAN -u $L2TP_LNSSERVER $L2TP_LNSPORT $L2TP_LNSPORT &
    local pscan_pid=$!

    while [ true ]; do
        if [ -f "$PORTSCAN_RESULT" ]; then
            rm -f $PORTSCAN_RESULT 
            return
        fi

        sleep 1
        idx=$((idx+1))
        [ $idx -gt $timeout ] && break
    done    

    kill $pscan_pid > /dev/null 2>&1
    logger -t "l2tpc" "Request packet can't reach the port of the L2TP Server used ($L2TP_LNSPORT) !" 
    logger -t "l2tpc" "May the packet drop by the server's firewall or your router behind the firewall !?"
    echo "Request packet can't reach the port of the Server used !"
    exit 1  
}  


#clear last ppp auth fail temp file
rm -rf /var/run/ppp_auth*

#if [ -r $L2TP_RESULT_FILE ] ; then
	l2tp-stop
#fi

L2TP_PHASE1_TYPE=`rdcsman 0x00060E00 u8`
if [ "$L2TP_PHASE1_TYPE" = 0 ] ; then

	udhcpc-action stop
	udhcpc-action start
	RET=$?
	[ $RET = 1 ] && exit 1
	
	IF_DNS1=`rdcsman 0x80035005 ipv4`
	IF_DNS2=`rdcsman 0x80035006 ipv4`
	[ -n "$IF_DNS1" ] && echo "nameserver $IF_DNS1" > $RESOLV_CONF.phase1
    [ -n "$IF_DNS2" ] && echo "nameserver $IF_DNS2" >> $RESOLV_CONF.phase1	

elif [ "$L2TP_PHASE1_TYPE" = 1 ] ; then 
	
	IF_IP=`rdcsman 0x00060300 ipv4`
	IF_NM=`rdcsman 0x00060400 ipv4`
	IF_GW=`rdcsman 0x00060500 ipv4`
	IF_DNS1=`rdcsman 0x00060700 ipv4`
	IF_DNS2=`rdcsman 0x00060800 ipv4`
	
	ifconfig $ETH $IF_IP netmask $IF_NM
	route add default gw $IF_GW dev $ETH
	
    rm -f $RESOLV_CONF
	[ -n "$IF_DNS1" ] && echo "nameserver $IF_DNS1" > $RESOLV_CONF
    [ -n "$IF_DNS2" ] && echo "nameserver $IF_DNS2" >> $RESOLV_CONF
    [ -n "$IF_DNS1" ] && echo "nameserver $IF_DNS1" > $RESOLV_CONF.phase1
    [ -n "$IF_DNS2" ] && echo "nameserver $IF_DNS2" >> $RESOLV_CONF.phase1
fi

# Get the ip of L2TP_LNSSERVER
if [ "$L2TP_LNSSERVER"  == "" ]; then
    logger -t "l2tp" "No Peer IP/Domain for L2TP client !"
    echo "No Peer IP/Domain for L2TP client !"
    exit 1  
fi
echo "L2TP_LNSSERVER=$L2TP_LNSSERVER"

# Check the connection between Server and Client
L2TP_DETECT_SERVER_BY_PORTSCAN=0
L2TP_DETECT_SERVER_BY_PING=1
L2TP_NO_DETECT=2
detect_type=`rdcsman 0x00061002 u8` #CSID_C_L2TP_CLI_DETECT_LNS
if [ $detect_type -eq $L2TP_DETECT_SERVER_BY_PORTSCAN ]; then
	if [ -f "$PORTSCAN" ]; then
		test_lns_port
	else
		echo "can't find $PORTSCAN utility !! Start the connection directly ..."
		logger -t "l2tp" "can't find $PORTSCAN utility !! Start the connection directly ..."
	fi                 
elif [ $detect_type -eq $L2TP_DETECT_SERVER_BY_PING ]; then
	test_lns_exist # old version 
else
    echo "Don't detect LNS in advance. Start the connection directly !"
fi

# Find the default route
echo "Find the default route"
sl_get_IP_NM_GW_in_ifconfig $ETH IF_IP IF_NM IF_GW

route del default
route add $L2TP_LNSSERVER gw $IF_GW dev $ETH	



if [ $CNT_FORCE -eq 1 ] ; then
	echo "L2TP force connect!"
    if [ -z "`ps | grep l2tpd | grep -v xl2tpd |grep -v grep`" ]; then
	    l2tpd -d 65535
    fi

	echo "l2tp-control start-session $L2TP_LNSSERVER"

	l2tp-control "start-session $L2TP_LNSSERVER" > $L2TP_RESULT_FILE
    
    cat $L2TP_RESULT_FILE
	CFG=`cat $L2TP_RESULT_FILE`
	for s in $CFG
	do
		if [ $s = "OK" ] ; then
			break
		else
			rm $L2TP_RESULT_FILE		
			exit 1
		fi		
	done	 
else
	CNTTYPE=`rdcsman 0x00060900 u32`
	if [ $CNTTYPE = 0 ] ; then

		wrcsman "0x80060200 0x00 && \
				 0x80060300 0x00 && \
				 0x80060400 0x00 && \
				 0x80060700 0x05 && \
				 0x80010002 0x00 && \
				 0x80010003 0x00 && \
				 0x80010004 0x00 && \
				 0x80010007 0x05"
                 
        if [ -z "`ps | grep l2tpd | grep -v xl2tpd |grep -v grep`" ]; then
		    l2tpd -d 65535
        fi
        
        if [ -z "`ps | grep "l2tp-ondemand -wan" | grep -v grep`" ]; then
            l2tp-ondemand -wan &
        fi
		exit 0
	else
        if [ -z "`ps | grep l2tpd | grep -v xl2tpd |grep -v grep`" ]; then
		    l2tpd -d 65535
        fi

		echo "l2tp-control start-session $L2TP_LNSSERVER"

		l2tp-control "start-session $L2TP_LNSSERVER" > $L2TP_RESULT_FILE

		cat $L2TP_RESULT_FILE
		CFG=`cat $L2TP_RESULT_FILE`
		for s in $CFG
		do
			if [ $s = "OK" ] ; then
				break
			else
				rm $L2TP_RESULT_FILE		
				exit 1
			fi		
		done	 
	fi
fi

# Monitor connection
TIME=0
TIMEOUT=10
while [ true ] ; do
	#l2tp_status > /dev/null 2>&1
	l2tp_status		

	if [ $? = 0 ] ; then
		echo "$0: Connected!"
		# Must wait till executing ip-up completely..
		sleep 1
		exit 0
    fi
    
	if [ -f /var/run/ppp_auth_fail ] ; then
		echo "$0: Authentication fail!"
		wrcsman "0x80010007 0x06 && \
				 0x80060700 0x06"
		rm -rf $L2TP_RESULT_FILE
		exit 0
	fi
		
    sleep 1
    TIME=$(($TIME+1))
	if [ $TIME -gt $TIMEOUT ] ; then
		echo "TIME_OUT" 
		rm -rf $L2TP_RESULT_FILE
		exit 1
	fi	
done

