#!/bin/sh

CONFIG=/etc/ppp/pppoe.conf

export CONFIG
. $CONFIG

. /usr/bin/scriptlib

PIDFILE_START="$PIDFILE.start"
PIDFILE_CONNECT="$PIDFILE.connect"
PIDFILE_PPPD="/var/run/ppp-pppoe.pid"

CNT_TYPE=`rdcsman 0x00040900 u16`

#clear last ppp auth fail tmp file
rm -rf /var/run/ppp_auth_fail

# Check for $PIDFILE.connect
if [ -r "$PIDFILE_CONNECT" ] ; then
    PID=`cat "$PIDFILE_CONNECT"`
    # Check if still running
    kill -0 $PID > /dev/null 2>&1
    if [ $? = 0 ] ; then
		echo "$0: There already seems to be a PPPoE connection up (PID $PID)" >& 2
		exit 0
    fi
    # Delete bogus PIDFILE
    rm -f "$PIDFILE_CONNECT" "$PIDFILE_START"
fi

echo $$ > $PIDFILE_START

pppoe-connect "$@" > /dev/null 2>&1 &
#pppoe-connect "$@" &

CONNECT_PID=$!

if [ "$CONNECT_TIMEOUT" = "" -o "$CONNECT_TIMEOUT" = 0 ] ; then
    exit 0
fi

# Don't monitor connection if dial-on-demand
if [ "$DEMAND" != "" -a "$DEMAND" != "no" ] ; then
	
	sleep 2 #Important! it must be waited for pppd creating the pppx interface	
	
	if [ -r $PIDFILE_PPPD ] ; then
		sl_get_ppp_PID_IFname $PIDFILE_PPPD PPP_PID PPP_IF
		[ $? != 0 ]&& exit 1 	
	else
		exit 1
	fi	
		
	sl_get_IP_NM_GW_in_ifconfig $PPP_IF IF_IP IF_NM IF_GW
	
	if [ "$IF_IP" = "10.64.64.64" ] ; then
	#Got a fake IP, interface is disconnect
		wrcsman "0x80040200 00 && \
				 0x80040300 00 && \
				 0x80040400 00 && \
				 0x80010002 00 && \
				 0x80010003 00 && \
				 0x80010004 00 "
		if [ $CNT_TYPE -eq 0 ] ; then
		#wait for traffic
			wrcsman "0x80040700 0x05 && \
				 	 0x80010007 0x05"
		else
		#manual or autoreconnect, but wan is unconnected.
			wrcsman "0x80040700 0x00 && \
				 	 0x80010007 0x00"
		fi
	else
	#Got a real IP address
		wrcsman "0x80040200 {$IF_IP} && \
				 0x80040300 {$IF_NM} && \
				 0x80040400 {$IF_GW} && \
				 0x80040700 0x02 && \
				 0x80010002 {$IF_IP} && \
				 0x80010003 {$IF_NM} && \
				 0x80010004 {$IF_GW} && \
				 0x80010007 0x02"
		
	fi
    exit 0
fi

# Monitor connection
TIME=0
CONNECT_POLL=1
CONNECT_TIMEOUT=20
while [ true ] ; do
    pppoe-status $CONFIG > /dev/null 2>&1
    #pppoe-status $CONFIG
    # Looks like the interface came up
    if [ $? = 0 ] ; then
		echo "$0: Connected!"
		#sleep 2  #Important! it must be waited for pppd writing the csids	
		exit 0
    fi

	if [ -f /var/run/ppp_auth_fail ] ; then
		echo "$0: Authentication Fail!"
		wrcsman	"0x80010007 0x06 &&\
				 0x80040700 0x06"
		exit 0
	fi

    sleep $CONNECT_POLL
    TIME=$(($TIME + $CONNECT_POLL))
    if [ $TIME -gt $CONNECT_TIMEOUT ] ; then
	break
    fi
done

echo "TIMED OUT" >& 2

# Clean up PIDFILE(s)
rm -f "$PIDFILE_START"

exit 1

