#!/bin/bash

if [ "$1" == 'install' ] ; then
	echo "installing"
	ln -s /usr/local/etc/if-local /sbin/ifup-local
	ln -s /usr/local/etc/if-local /sbin/ifdown-local
	ln -s /usr/local/etc/if-local /etc/ppp/ip-up.local
	ln -s /usr/local/etc/if-local /etc/ppp/ip-down.local
	exit 0
	fi

# this script should be called after the system is finished setting up the interface; ip address and all.

PROG=`basename $0`
HOST=`hostname`
exec >>/tmp/LOG.$PROG 2>&1
echo ===================== start $0 $@
date
LOGGER="logger -t $PROG"
echo "$0 $@"
$LOGGER "$0 $@"

case "$PROG" in
	ifup-local|ip-up.local)     MODE=up   ;;
	ifdown-local|ip-down.local) MODE=down ;;
	*) echo "ABORT: unknown \$0=$PROG" ; exit 9 ;;
esac

#######################
## begin subroutines ##

print_ip()
{
	ifconfig $1 | grep 'inet addr' | cut -f2 -d: | cut -f1 -d' '
}

print_ip_far()
{
#	inet addr:10.10.220.2  P-t-P:172.16.32.129  Mask:255.255.255.255
	ifconfig $1 | grep 'inet addr' | cut -f3 -d: | cut -f1 -d' '
}

##  end subroutines  ##
#######################

if [ 'x' = "x$@" ] ; then
	if [ 'x' != "x$PPP_IFACE" ] ; then
		# kubuntu uses envs instead of cmd line args
		set "$PPP_IFACE" "$PPP_TTY" "$PPP_SPEED" "$PPP_LOCAL" "$PPP_REMOTE" "$PPP_IPPARAM"
		fi
	fi

echo "args=[$@]"

# what is our location?  what is this interface doing?
case "$@" in
	# dhcp config'ed if only gives the interface name
	eth*)
		IF=$1
		IP=`print_ip $IF`
		case $IP in
		*)
			echo "Unknown location IF=$IF IP=$IP"
			ifconfig $IF
			LOCATION=unknown
			;;
		esac
		;;
	ppp*)
		# ppp args:
		# 1:interface-name  2:tty-device  3:speed  4:local-IP 5:remote-IP 6:ipparam
		IF=$1
		#IP=`print_ip $IF`
		IP=$4
		PARAMS=$6
		case $PARAMS in
		BluetoothDialup) LOCATION=BluetoothDialup ;;
		*)
			echo "Unknown location IF=$IF IP=$IP"
			ifconfig $IF
			LOCATION=unknown
			;;
		esac
#		case $IP in
#		*)
#			LOCATION=unknown     
#			echo "Unknown location IF=$IF IP=$IP"
#			ifconfig $IF
#			;;
#   esac
		;;
	*)
		echo "ERROR: unknown args [$@]"
		exit 8
		;;
esac

/usr/local/etc/network_config $MODE $LOCATION $IF $IP

exit 0
