#!/bin/sh

CONFIG=/etc/ppp/3g.conf

export CONFIG
. $CONFIG

. /usr/bin/scriptlib

PIDFILE_START="$PIDFILE.start"
PIDFILE_CONNECT="$PIDFILE.connect"
PIDFILE_PPPD="/var/run/ppp-3g.pid"
PIDFILE_PPPD_BAK="/var/run/bak.ppp-3g.pid"

CNT_TYPE=`rdcsman 0x001e000a u16`

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

# Check for /var/run/3g.pid.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 3G PPP connection up (PID $PID)" >& 2
		exit 0
    fi
    # Delete bogus PIDFILE
    rm -f "$PIDFILE_CONNECT" "$PIDFILE_START"
fi

echo $$ > $PIDFILE_START

3g-connect "$@"> /dev/null 2>&1 &

CONNECT_PID=$!

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

# Don't monitor connection if dial-on-demand
if [ $CNT_TYPE -eq 0 ] ; then
	sleep 6 #Important! it must be waited for pppd creating the pppx interface	 and ppp-3g.pid
	
	if [ -r $PIDFILE_PPPD ] ; then
		cp $PIDFILE_PPPD $PIDFILE_PPPD_BAK
		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 "0x801e0200 00 && \
                 0x801e0300 00 && \
                 0x801e0400 00 && \
                 0x80010002 00 && \
                 0x80010003 00 && \
                 0x80010004 00 "
    #wait for traffic
        wrcsman "0x801e0700 0x05 && \
                 0x80010007 0x05"
	elif [ "$IF_IP" = "" ] ; then
    #Got no IP, interface is disconnect
        wrcsman "0x801e0200 00 && \
                 0x801e0300 00 && \
                 0x801e0400 00 && \
                 0x80010002 00 && \
                 0x80010003 00 && \
                 0x80010004 00 "
    #disconnecting
        wrcsman "0x801e0700 0x03 && \
                 0x80010007 0x03"
	else
    #Got a real IP address
		wrcsman "0x801e0200 {$IF_IP} && \
				 0x801e0300 {$IF_NM} && \
				 0x801e0400 {$IF_GW} && \
				 0x801e0700 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=30
while [ true ] ; do

	cp $PIDFILE_PPPD $PIDFILE_PPPD_BAK

    3g-status $CONFIG > /dev/null 2>&1
    # Looks like the interface came up

	if [ $? = 0 ] ; then
		echo "$0: Connected!"
		exit 0
    fi

	if [ -f /var/run/ppp_auth_fail ] ; then
		echo "$0: Authentication Fail!"
		wrcsman "0x80010007 0x06 &&\
				0x801e0700 0x06 &&\
				0x801e1100 0x05"
		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

