#!/bin/sh
# Copyright (c) 2004-2005 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header$

# Contributed by Roy Marples (uberlord@gentoo.org)

action=${1}
echo ${action}

case "${action}" in
	bound|renew|deconfig)
		# We handle these actions
		;;
	nak|leasefail)
		# These are valid actions, but we don't handle them
		exit 0
		;;
	*)
		echo "We don't handle that action" >&2
		exit 1
		;;
esac

[[ ${action} == nak ]] && exit 0

# Fix any potential localisation problems
# Note that LC_ALL trumps LC_anything_else according to locale(7)
ifconfig() {
	LC_ALL=C /sbin/ifconfig "$@"
}

ip=${ip// }
subnet=${subnet// }
broadcast=${broadcast// }
[[ -n ${broadcast} ]] && broadcast="broadcast ${broadcast}"

# If the current address does not match or we are deconfiguring
# then we take the all the addresses on the interface down
cur=$( ifconfig ${interface} | grep 'inet ' | awk -F: '{ print $2,$3 }' | awk '{ print $1,$3 }' )
if [[ ${cur} != "${ip} ${subnet}" || ${action} == deconfig ]]; then
	# Remove all aliases
	for i in $( ifconfig | grep -o "^${interface}:[0-9]*" | tac | xargs ); do
		ifconfig ${i} down
	done

	# Remove all addresses
	while ifconfig ${interface} | grep -q -m1 -o 'inet addr:[^ ]*' ; do
		ifconfig ${interface} 0.0.0.0 || break
	done
fi

/sbin/ifconfig ${interface} up

[[ -z ${MODULES_DIR} ]] && MODULES_DIR=/lib/rcscripts/net.modules.d
source ${MODULES_DIR}/helpers.d/config-system

if [[ ${action} == deconfig ]]; then
	restore_configs
	exit 0
fi

# Configure our IP address
ifconfig ${interface} inet ${ip} netmask ${subnet} ${broadcast}

eval dhcp=\" \$\{dhcp_${interface}\} \"
if [[ ${dhcp} != *' nogateway '* ]]; then
    # Configure our routers
    for r in ${router}; do
	while true; do
	    /sbin/route del 0.0.0.0 2>/dev/null || break
	done

	# We can only have one default route!
	/sbin/route add default gw ${r} dev ${interface} && break
    done
fi

# Set our module to udhcpc if it's not set
[[ -z ${module} ]] && module=udhcpc

config_system >/dev/null

exit 0
