#!/bin/sh

[ "$IFACE" == "hso0" ] || exit 0

TTY=${IF_HSO_DEVICE:-/dev/usb/tth/0}
[ -c "$TTY" ] || exit 0

if [ "$IF_UMTS_PINCODE" ]; then
	COMGTPIN="$IF_UMTS_PINCODE" comgt -d "$TTY" PIN
fi

if [ "$IF_UMTS_APN" ]; then
	COMGTAPN="$IF_UMTS_APN" comgt -d "$TTY" APN
fi

if [ "$IF_HSO_USERNAME" ]; then
        USER="$IF_HSO_USERNAME" PASS="${IF_HSO_PASSWORD}" comgt -s -d "$TTY" /etc/comgt/hsoauth.comgt
fi

# only run once!
[ -f /tmp/hso-connect ] && exit 0

while :
do
        # get connection status
        STATUS=$(comgt -s -d "$TTY" /etc/comgt/hsostatus.comgt |
                 tr -d " " |
                 grep -v ^$ |
                 cut -d , -f 2)
        # dial if connection status is disabled
        if [ "$STATUS" -eq "0" ] ; then
                comgt -s -d "$TTY" /etc/comgt/hsoconnect.comgt
                DATA=$(comgt -s -d "$TTY" /etc/comgt/hsodata.comgt)
		if [ "$?" -ne 0 ] ; then
			continue
		fi
                DATA=$(echo $DATA |
                       tr -d " " |
                       grep -v ^$)
                IP=$(echo $DATA | cut -d , -f 2)
                NS1=$(echo $DATA | cut -d , -f 4)
                NS2=$(echo $DATA | cut -d , -f 5)
                ip address flush dev hso0 2> /dev/null
                ip address add "$IP/32" dev hso0
                ip link set hso0 up
                ip route add default dev hso0
                echo "nameserver $NS1" >  /tmp/resolv.conf
                echo "nameserver $NS2" >> /tmp/resolv.conf
        fi
        sleep 10
done &

echo $! > /tmp/hso-connect

