#!/bin/sh
# Copyright (c) 2004-2005 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Header: /var/cvsroot/gentoo-src/rc-scripts/net-scripts/net.modules.d/helpers.d/Attic/udhcpc-iproute2,v 1.16.2.1 2005/01/25 10:42:54 uberlord Exp $

# 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 addr flush dev ${interface} scope global &>/dev/null
	ip 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 addr flush dev ${interface} scope global &>/dev/null
	ip addr flush dev ${interface} scope host &>/dev/null
	ip addr add dev ${interface} ${ip}/${cidr} ${broadcast}
	echo "flushed" > /tmp/action
fi

# Configure our default route
x=$(ip route show | awk '{ if ($1 == "default") {print $3} }')
for r in ${router}; do
	# ip route doesn't pad 0's, so we strip any padding if we have any
	r=${r//000/0}
	r=${r//00/0}

	# 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

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

config_system

exit 0
