#!/bin/sh
########################################################################
# Begin $network_devices/services/ipv4-static
#
# Description : IPV4 Static Boot Script
#
# Authors     : Nathan Coulson - nathan@linuxfromscratch.org
#		Kevin P. Fleming - kpfleming@linuxfromscratch.org
#
# Version     : 00.00
#
# Notes       :
#
########################################################################

. /etc/sysconfig/rc 
. ${rc_functions} 
. ${IFCONFIG}

if [ -z "${VLAN}" ]
then
	boot_mesg "VLAN variable missing from ${IFCONFIG}, cannot continue." ${FAILURE}
	echo_failure
	exit 1
fi

if [ -z "${IP}" ]
then
	boot_mesg "IP variable missing from ${IFCONFIG}, cannot continue." ${FAILURE}
	echo_failure
	exit 1
fi

if [ -z "${PREFIX}" -a -z "${PEER}" ]
then
	boot_mesg -n "PREFIX variable missing from ${IFCONFIG}," ${WARNING}
	boot_mesg " assuming 24."
	echo_warning
	PREFIX=24
	args="${args} ${IP}/${PREFIX}"
elif [ -n "${PREFIX}" -a -n "${PEER}" ]
then
	boot_mesg "PREFIX and PEER both specified in ${IFCONFIG}, cannot continue." ${FAILURE}
	echo_failure
	exit 1
elif [ -n "${PREFIX}" ]
then
	args="${args} ${IP}/${PREFIX}"
elif [ -n "${PEER}" ]
then
	args="${args} ${IP} peer ${PEER}"
fi

if [ -n "${BROADCAST}" ]
then
	args="${args} broadcast ${BROADCAST}"
fi

if [ -n "${SOURCE}" ]
then
	args="${args} src ${SOURCE}"
fi

case "${2}" in
	up)
		boot_mesg "Adding VLAN ${VLAN} to the ${LINK} interface..."
		vconfig add ${LINK} ${VLAN}
		evaluate_retval

		link_status=`ip link show ${1} 2> /dev/null`
		if [ -n "${link_status}" ]
		then
			if ! echo "${link_status}" | grep -q UP
			then
				boot_mesg "Bringing up the ${LINK}.${VLAN} interface..."
				ip link set ${LINK}.${VLAN} up
				evaluate_retval
			fi
		fi

		boot_mesg "Adding IPv4 address ${IP} to the ${1} interface..."
		ip addr add ${args} dev ${1}
		evaluate_retval
	
		if [ -n "${GATEWAY}" ]
		then
			if ip route | grep -q default
			then
				boot_mesg "Gateway already setup; skipping." ${WARNING}
				echo_warning
			else
				boot_mesg "Setting up default gateway..."
				ip route add default via ${GATEWAY} dev ${1}
				evaluate_retval
			 fi
		fi
	;;
	
	down)
		if [ -n "${GATEWAY}" ]
		then
			boot_mesg "Removing default gateway..."
			ip route del default
			evaluate_retval
		fi
	
		boot_mesg "Removing IPv4 address ${IP} from the ${1} interface..."
		ip addr del ${args} dev ${1}
		evaluate_retval

		boot_mesg "Removing VLAN ${VLAN} from the ${LINK} interface..."
		vconfig rem ${LINK}.${VLAN}
		evaluate_retval
	;;
	
	*)
		echo "Usage: ${0} [interface] {up|down}"
		exit 1
	;;
esac

# End $network_devices/services/ipv4-static
