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

ip=${ip// }
ip=${ip//000/0}
ip=${ip//00/0}
subnet=${subnet// }
subnet=${subnet//000/0}
subnet=${subnet//00/0}
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

	# Remove IPv6 addresses
	for i in $( ifconfig ${interface} | awk '$1=="inet6" && $4!="Scope:Link" {print $3}' ); do
		ifconfig ${interface} inet6 del ${i}
	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}

# 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

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

config_system

exit 0
