#!/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)
ip() {
	LC_ALL=C /sbin/ip "$@"
}

# We don't flush the link local address
ip link set up dev ${interface} &>/dev/null

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

if [[ ${action} == deconfig ]]; then
	ip -f inet addr flush dev ${interface} scope global &>/dev/null
	ip -f inet addr flush dev ${interface} scope host &>/dev/null
	restore_configs
	exit 0
fi

# Configure our IP address
ip=${ip// }
subnet=${subnet// }
cidr=$( netmask2cidr ${subnet} )
broadcast=${broadcast// }
[[ -n ${broadcast} ]] && broadcast="broadcast ${broadcast}"

# If we don't have our address then we flush it and then add our new one
ip -family inet addr show scope global dev ${interface} | grep inet | grep -q "${ip}/${cidr}"
if [[ $? == 1 ]] ; then
	ip -f inet addr flush dev ${interface} scope global &>/dev/null
	ip -f inet addr flush dev ${interface} scope host &>/dev/null
	ip addr add dev ${interface} ${ip}/${cidr} ${broadcast}
	echo "flushed" > /tmp/action
fi

eval dhcp=\" \$\{dhcp_${interface}\} \"
if [[ ${dhcp} != *' nogateway '* ]]; then
    # Configure our default route
    x=$(ip route show | awk '{ if ($1 == "default") {print $3} }')
    for r in ${router}; do
	# We can only have one default route!
	if [[ -z ${x} ]]; then
	    ip route add default via ${r} dev ${interface} 2>/dev/null && break
	elif [[ ${x} != ${r} ]]; then
	    ip route change default via ${r} dev ${interface} 2>/dev/null && break
	fi
    done
fi

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

config_system >/dev/null

exit 0
