#!/bin/sh

umask 077

copy() {
    cp $1 $2
    if [ "$?" != 0 ] ; then
	echo "*** Error copying $1 to $2"
	echo "*** Quitting."
	exit 1
    fi
}

. /opt/pppoe-dialer/pppoe-dialer-functions

RP_PPPOE_DIR="/opt/usr/sbin"
if [ -e /usr/sbin/pppoe-connect ]; then
	RP_PPPOE_DIR="/usr/sbin"
fi  

post_pppoe_connect() {
	#make sure /etc/resolv.conf exists
	if [ ! -x /etc/resolv.conf ]; then
		cp /etc/ppp/resolv.conf /etc/resolv.conf > /dev/null 2>&1
		chmod a+r /etc/resolv.conf > /dev/null 2>&1
	fi
	
	#Check if ppp interface is set as default gw route
	IF="ppp0" #assumption
	status_output="`$RP_PPPOE_DIR/pppoe-status /etc/ppp/connections/$1`"
	echo $status_output | grep -E 'up|running' > /dev/null
	if [ $? -eq 0 ]; then
		IF="`$RP_PPPOE_DIR/pppoe-status /etc/ppp/connections/$1 | grep "running on interface" | awk -F 'running on interface' '{print $2}' | sed s/\ //g`"
	fi
	echo $IF | grep ppp > /dev/null
	if [ $? -eq 0 ]; then
		#Find PPP IP Address
		IPADDR=`/sbin/ifconfig $IF | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1 }' | sed s/\ //g`

		default_addr="`route -n | tail -n 1 | awk '{print $2}'`"

		if [ $default_addr != "$IPADDR" ]; then
			#ppp address is not default gw route
			#set it as default route
			route del default
			route add default gw $IPADDR dev $IF
		fi
	fi
}

unloadKernelModules() {
	#not sure if necessary, but maybe optimal?
	#maybe especially for pppoe, which is listed as experimental for the default Maemo 5 kernel.
        if test `uname -s` = Linux ; then
            # For 2.4 kernels.  Will fail on 2.2.x, but who cares?
            modprobe -r ppp_generic > /dev/null 2>&1
            modprobe -r ppp_async > /dev/null 2>&1
            modprobe -r ppp_synctty > /dev/null 2>&1

            modprobe -r pppox > /dev/null 2>&1
            modprobe -r pppoe > /dev/null 2>&1
        fi
}

if [ ! -d /etc/ppp/connections ]; then
    mkdir -p /etc/ppp/connections
fi

# $1 - control params (newaccount, editaccount, delaccount)
# control param - newaccount
#	$2 - username
#	$3 - connection name
#	$4 - service name
#	$5 - password
#
# control param - newaccount
#	$2 - username
#	$3 - connection name
#	$4 - service name
#	$5 - password
#
# control param - delaccount
#	$2 - connection name
#	$3 - username
# 
# control param - connect
#	#2 - connection name
#
# control param - disconnect
#	#2 - connection name
#
# control param - status
#	#2 - connection name
#                                                                      
# control param - checkuser                                               
#       #2 - username
# 
# control param - checkuser                                            
#       #2 - connection name   
# 
# control param - checkaccount
#	#2 - connection name
#
# control param - listaccounts
#	no additional params

if [ $1 = "newaccount" ]; then
	echo "pppoegui-backend: new account $1 $2 $3 $4 $5"
	#sometimes residues of backup files are left
	#quick fix
	rm -rf /etc/ppp/*.bak
	rm -rf /etc/ppp/connections/*.bak
	sed -e "s&^USER=.*&USER='$2'&" \
	    -e "s&^ETH=.*&ETH='wlan0'&" \
	    -e "s&^PIDFILE=.*&PIDFILE=\"/var/run/$3-pppoe.pid\"&" \
	    -e "s/^FIREWALL=.*/FIREWALL=NONE/" \
	    -e "s/^DEMAND=.*/DEMAND=no/" \
	    -e "s/^DNSTYPE=.*/DNSTYPE=SERVER/" \
	    -e "s/^DNS1=.*/DNS1=/" \
	    -e "s/^DNS2=.*/DNS2=/" \
	    -e "s/^PEERDNS=.*/PEERDNS=yes/" \
	    -e "s/^SERVICENAME=.*/SERVICENAME=$4/" \
	    -e "s/^LINUX_PLUGIN=.*/LINUX_PLUGIN=\/opt\/usr\/lib\/pppd\/2.4.5\/rp-pppoe.so/" \
	    < /etc/ppp/pppoe.conf.template > /etc/ppp/connections/$3

	RET=$?
	if [ $RET -eq 1 ]; then
		exit 1
	fi

	touch /etc/ppp/chap-secrets #just in case it doesnt exist
	cat /etc/ppp/chap-secrets | grep -v $2 > /etc/ppp/chap-secrets
	grep $2 /etc/ppp/chap-secrets > /dev/null
	RET=$?
	if [ $RET -eq 0 ]; then
		#error:username already in chap-secrets
		cp /etc/ppp/$3.bak /etc/ppp/connections/$3
		rm -rf /etc/ppp/connections/$2
		exit 1
	fi

	touch /etc/ppp/pap-secrets #just in case it doesnt exist
	cat /etc/ppp/pap-secrets | grep -v $2 > /etc/ppp/pap-secrets
	grep $2 /etc/ppp/pap-secrets > /dev/null
	RET=$?
	if [ $RET -eq 0 ]; then
		#error:username already in pap-secrets
		cp /etc/ppp/$3.bak /etc/ppp/connections/$3
		rm -rf /etc/ppp/connections/$2
		exit 1
	fi

	if [ -r /etc/ppp/pap-secrets ] ; then
	    copy /etc/ppp/pap-secrets /etc/ppp/pap-secrets-bak
	else
	    cp /dev/null /etc/ppp/pap-secrets-bak
	fi
	if [ -r /etc/ppp/chap-secrets ] ; then
	    copy /etc/ppp/chap-secrets /etc/ppp/chap-secrets-bak
	else
	    cp /dev/null /etc/ppp/chap-secrets-bak
	fi

	egrep -v "^$2|^\"$2\"" /etc/ppp/pap-secrets-bak > /etc/ppp/pap-secrets
	echo "\"$2\"	*	\"$5\"" >> /etc/ppp/pap-secrets
	egrep -v "^$2|^\"$2\"" /etc/ppp/chap-secrets-bak > /etc/ppp/chap-secrets
	echo "\"$2\"	*	\"$5\"" >> /etc/ppp/chap-secrets

	RET=$?
	if [ $RET -eq 0 ]; then
		rm -rf /etc/ppp/$3.bak
		rm -rf /etc/ppp/chap-secrets-bak
		rm -rf /etc/ppp/pap-secrets-bak
	fi
	exit $RET
elif [ $1 = "editaccount" ]; then
	echo "pppoegui-backend: edit account $1 $2 $3 $4 $5"
	cp /etc/ppp/connections/$3 /etc/ppp/$3.bak
	oldPwd="`grep USER /etc/ppp/connections/$3 | sed s/USER=// | sed s/\'//g`"
	rm /etc/ppp/connections/$3
	sed -e "s&^USER=.*&USER='$2'&" \
	    -e "s&^ETH=.*&ETH='wlan0'&" \
	    -e "s&^PIDFILE=.*&PIDFILE=\"/var/run/$3-pppoe.pid\"&" \
	    -e "s/^FIREWALL=.*/FIREWALL=NONE/" \
	    -e "s/^DEMAND=.*/DEMAND=no/" \
	    -e "s/^DNSTYPE=.*/DNSTYPE=SERVER/" \
	    -e "s/^DNS1=.*/DNS1=/" \
	    -e "s/^DNS2=.*/DNS2=/" \
	    -e "s/^PEERDNS=.*/PEERDNS=yes/" \
	    -e "s/^SERVICENAME=.*/SERVICENAME=$4/" \
	    -e "s/^LINUX_PLUGIN=.*/LINUX_PLUGIN=\/opt\/usr\/lib\/pppd\/2.4.5\/rp-pppoe.so/" \
	    < /etc/ppp/$3.bak > /etc/ppp/connections/$3
	RET=$?
	if [ $RET -eq 1 ]; then
		echo "editing $3 pppoe config did not succeed"
		cp /etc/ppp/$3.bak /etc/ppp/connections/$3
	else
		echo "editing $3 pppoe config ok; updating pap and chap pwd files"

		touch /etc/ppp/chap-secrets
		touch /etc/ppp/pap-secrets

		cp /etc/ppp/chap-secrets /etc/ppp/chap-secrets.bk
		cp /etc/ppp/pap-secrets /etc/ppp/pap-secrets.bk

		echo "oldPwd is $oldPwd (newPwd is $2)"
		sed -i '/'$oldPwd'/ d' /etc/ppp/chap-secrets > /etc/ppp/chap-secrets
		grep $oldPwd /etc/ppp/chap-secrets > /dev/null
		RET=$?
		if [ $RET -eq 0 ]; then
			echo "couldnt remove username from chap-secrets"
			cp /etc/ppp/$3.bak /etc/ppp/connections/$3
			mv /etc/ppp/chap-secrets.bk /etc/ppp/chap-secrets
			exit 1
		fi

		sed -i '/'$oldPwd'/ d' /etc/ppp/pap-secrets > /etc/ppp/pap-secrets
		grep $oldPwd /etc/ppp/pap-secrets > /dev/null
		RET=$?
		if [ $RET -eq 0 ]; then
			echo "couldnt remove username from pap-secrets"
			cp /etc/ppp/$3.bak /etc/ppp/connections/$3
			mv /etc/ppp/chap-secrets.bk /etc/ppp/chap-secrets
			mv /etc/ppp/pap-secrets.bk /etc/ppp/pap-secrets
			exit 1
		fi

		echo "removed old pwd data from pap/chap files; replacing with new user/pwds"
		if [ -r /etc/ppp/pap-secrets ] ; then
		    copy /etc/ppp/pap-secrets /etc/ppp/pap-secrets-bak
		else
		    cp /dev/null /etc/ppp/pap-secrets-bak
		fi
		if [ -r /etc/ppp/chap-secrets ] ; then
		    copy /etc/ppp/chap-secrets /etc/ppp/chap-secrets-bak
		else
		    cp /dev/null /etc/ppp/chap-secrets-bak
		fi

		egrep -v "^$2|^\"$2\"" /etc/ppp/pap-secrets-bak > /etc/ppp/pap-secrets
		echo "\"$2\"	*	\"$5\"" >> /etc/ppp/pap-secrets
		egrep -v "^$2|^\"$2\"" /etc/ppp/chap-secrets-bak > /etc/ppp/chap-secrets
		echo "\"$2\"	*	\"$5\"" >> /etc/ppp/chap-secrets

		rm /etc/ppp/chap-secrets.bk
		rm /etc/ppp/pap-secrets.bk
	
		RET=0
	fi
	rm -rf /etc/ppp/$3.bak

	exit $RET
elif [ $1 = "delaccount" ]; then
	echo "pppoegui-backend: delete account $1 $2 $3" 
	cp /etc/ppp/connections/$2 /etc/ppp/$2.bak
	rm /etc/ppp/connections/$2
	ls /etc/ppp/connections/$2
	RET=$?
	if [ $RET -eq 1 ]; then
		echo "file was deleted; now remove usernames from pap and chap files"
		sed -i '/'$3'/ d' /etc/ppp/chap-secrets > /etc/ppp/chap-secrets
		grep $3 /etc/ppp/chap-secrets > /dev/null
		RET=$?
		if [ $RET -eq 0 ]; then
			echo "couldnt remove username from chap-secrets"
			mv /etc/ppp/$2.bak /etc/ppp/connections/$2
			exit 1
		fi

		sed -i '/'$3'/ d' /etc/ppp/pap-secrets > /etc/ppp/pap-secrets
		grep $3 /etc/ppp/pap-secrets > /dev/null
		RET=$?
		if [ $RET -eq 0 ]; then
			echo "couldnt remove username from pap-secrets"
			mv /etc/ppp/$2.bak /etc/ppp/connections/$2
			exit 1
		fi
		echo "updated chap and pap files"
	fi
	rm -rf /etc/ppp/connections/$2
	ls /etc/ppp/connections/$2
	RET=$?
	if [ $RET -eq 1 ]; then
		echo "file was removed; pap/chap username removal went ok"
		exit 0
	else
		echo "file wasnt removed; deletion failed"
		exit 1
	fi
	exit 0
elif [ $1 = "connect" ]; then
	echo "pppoegui-backend: connect $1 $2" 
	$RP_PPPOE_DIR/pppoe-start /etc/ppp/connections/$2 &	
	exit 0
elif [ $1 = "connect_wait" ]; then
	echo "pppoegui-backend: connect_wait $1 $2" 
	$RP_PPPOE_DIR/pppoe-start /etc/ppp/connections/$2
	pppoe_start_pid=$_
	echo "pppoe-start pid is $pppoe_start_pid"
	wait $pppoe_start_pid
	RET=$?
	exit $RET
elif [ $1 = "auto-connect" ]; then
	/opt/pppoe-dialer/pppoe_connect &
elif [ $1 = "post-connect" ]; then
	post_pppoe_connect $2
elif [ $1 = "disconnect" ]; then
	echo "pppoegui-backend: disconnect $1 $2"
	#Failsafe purpose - give a bit of time to make sure disconnect happens
	IF="ppp0" #assumption
	status_output="`$RP_PPPOE_DIR/pppoe-status /etc/ppp/connections/$2`"
	echo $status_output | grep -E 'up|running' > /dev/null
	if [ $? -eq 0 ]; then
		IF="`$RP_PPPOE_DIR/pppoe-status /etc/ppp/connections/$2 | grep "running on interface" | awk -F 'running on interface' '{print $2}' | sed s/\ //g`"
		attempts=0
		while [ $? -eq 0 ];
		do
			attempts=`expr $attempts + 1`
			if [ $attempts -gt 4 ]; then
				break
			fi
			$RP_PPPOE_DIR/pppoe-stop /etc/ppp/connections/$2
			sleep 2
			ifconfig $IF > /dev/null 2>&1
		done
	fi
	RET=$?
	disconnectManually
	rm -rf /etc/resolv.conf
	exit $RET
elif [ $1 = "unloadKernelModules" ]; then
	unloadKernelModules
	#dummy=1
elif [ $1 = "status" ]; then
	echo "pppoegui-backend: status $1 $2" 
	$RP_PPPOE_DIR/pppoe-status /etc/ppp/connections/$2
	RET=$?
	if [ $RET -eq 0 ]; then
		IF="ppp0" #assumption
		IPADDR=""
		status_output="`$RP_PPPOE_DIR/pppoe-status /etc/ppp/connections/$2`"
		echo $status_output | grep -E 'up|running' > /dev/null
		if [ $? -eq 0 ]; then
			IF="`$RP_PPPOE_DIR/pppoe-status /etc/ppp/connections/$2 | grep "running on interface" | awk -F 'running on interface' '{print $2}' | sed s/\ //g`"
		fi
		echo $IF | grep ppp > /dev/null
		if [ $? -eq 0 ]; then
			#Find PPP IP Address
			IPADDR=`/sbin/ifconfig $IF | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1 }' | sed s/\ //g`
		fi
		echo "$IF;$IPADDR"
	else
		echo "Not connected"
	fi
	exit $RET
elif [ $1 = "checkuser" ]; then                                           
        echo "pppoegui-backend: checkuser $1 $2" 
	username=$2
	matches="`grep $2 /etc/ppp/connections/*`"
	RET=$?
	if [ $RET -eq 0 ]; then
		for match in $matches
		do
			user="`echo $match | awk -F'USER=' '{print $2}' | sed s/\'//g`"
			if [ $user == "$username" ]; then
				#match found
				exit 0
			fi
		exit 1
		done
	fi
	exit $RET
elif [ $1 = "getuser" ]; then                                       
        echo "pppoegui-backend: getuser $1 $2"                       
        grep USER= /etc/ppp/connections/$2
elif [ $1 = "getpwd" ]; then
        echo "pppoegui-backend: getpwd $1 $2"                       
        grep $2 /etc/ppp/pap-secrets | awk '{print $3}' | sed s/\"//g
elif [ $1 = "checkaccount" ]; then                 
	echo "pppoegui-backend: checkaccount $1 $2"
	ls /etc/ppp/connections/$2
	ret=$?
	if [ $ret -ne 0 ]; then	
		ret=1
	fi
	exit $ret
elif [ $1 = "listaccounts" ]; then
	ls -1 /etc/ppp/connections/ | grep -v pppoe.conf
elif [ $1 = "listwifinetworks" ]; then
	wifinetworks="`gconftool -R /system/osso/connectivity/IAP | grep -E 'IAP|wlan_ssid|name' | grep -A 1 -B 1 wlan_ssid | grep -v "name = " | grep -v wlan_ssid | grep -v '\-\-' | sed s/://g | awk -F'IAP\/' '{print $2}'`"

	for wifinetwork in $wifinetworks
	do
		network_gconf_name=$wifinetwork
		network_name="`gconftool --get /system/osso/connectivity/IAP/$wifinetwork/name`"
		wlan_ssid="`gconftool --get /system/osso/connectivity/IAP/$wifinetwork/wlan_ssid`"
		pppoe_account="`gconftool --get /system/osso/connectivity/IAP/$wifinetwork/pppoe_account`"
		echo $pppoe_account | grep "No value set for" > /dev/null
		ret=$?
		if [ $ret -eq 0 ]; then
			#no pppoe_account specified
			pppoe_account=""
		fi
		wlan_ssid="`echo $wlan_ssid | sed s/'\['//g | sed s/'\]'//g | sed s/,/\ /g`"
		wlssid=$wlan_ssid
		wlan_ssid=""
		for dec in $wlssid
		do
			chr=$(ascii $dec)
			wlan_ssid="`echo $wlan_ssid$chr`"
		done
		echo "NETWORK_NAME_$network_name,WLAN_SSID_$wlan_ssid,WIFI_GCONF_$wifinetwork,PPPOE_ACC_NAME_$pppoe_account"
	done
elif [ $1 = "addautostart" ]; then
	wifinetwork=$2
	outp="`gconftool --type string --set /system/osso/connectivity/IAP/$wifinetwork/pppoe_account $3`"
elif [ $1 = "removeautostart" ]; then
	wifinetwork=$2
	cur_acc_name="`gconftool --get /system/osso/connectivity/IAP/$wifinetwork/pppoe_account`"
	if [ $cur_acc_name == $3 ]; then
		outp="`gconftool --type string --set /system/osso/connectivity/IAP/$wifinetwork/pppoe_account None`"
	fi
fi
