#!/bin/bash

. $SCRIPTDIR/functions
pickup_options

try_static()
{
	xargise_file $MYIFACEDIR/ipv4address "$IP -4 address add dev $NAME"
}

try_dhcp()
{
	[ -x "$DHCP_CLIENT" ] || {
		print_error "$DHCP_CLIENT does not exist or is not executable. Try installing dhcpcd RPM."
		return 1
	}
	if need_detection; then
		if check_eth_link $NAME; then
			print_progress
		else
			print_nack
			return 1
		fi
	fi
	if [ -n "$DHCP_HOSTNAME" ]; then
		case "$DHCP_HOSTNAME" in
			AUTO)
				DHCP_ARGS="$DHCP_ARGS -H"
			;;
			localhost)
				[ -n "$HOSTNAME" -a "$HOSTNAME" != "localhost" -a "$HOSTNAME" != "localhost.localdomain" ] && DHCP_ARGS="$DHCP_ARGS -h $HOSTNAME"
			;;
			*)
				DHCP_ARGS="$DHCP_ARGS -h $DHCP_HOSTNAME"
			;;
		esac
	fi
	$DHCP_CLIENT $DHCP_ARGS -d -t $DHCP_TIMEOUT $NAME >/dev/null
	local RET=$?
	# dhcpcd sets iface down on failure, breaking dhcp-* BOOTPROTOs
	if [ "$RET" != "0" ]; then
		print_nack
		! is_yes $KEEP_DOWN && $IP link set dev $NAME up
	else
		print_progress
	fi
	return $RET
}

try_ipv4ll()
{
	[ -x "$ZCIP_CLIENT" ] || {
		print_error "$ZCIP_CLIENT does not exist or is not executable. Try installing zcip RPM."
		return 1
	}
	if need_detection; then
		if check_eth_link $NAME; then
			print_progress
		else
			print_nack
			return 1
		fi
	fi
	$ZCIP_CLIENT -s -i $NAME
	local RET=$?
	if [ "$RET" != "0" ]; then
		print_nack
	else
		print_progress
	fi
	return $RET
}

config_routes_rules()
{
	# setup routes
	local SRCFILE=`profiled_filename $MYIFACEDIR/ipv4route`
	[ -s "$SRCFILE" ] && $DENOISE "$SRCFILE" | \
	while read FIRST REST; do
	# If there is no operation, substitute default, otherwise keep.
		case "$FIRST" in
			add|del|change|append|replace)
				$IP -4 route $FIRST $REST
			;;
			*)
				$IP -4 route $DEFAULT_IPV4ROUTE_CMD $FIRST $REST
			;;
		esac
		print_progress
	done

	# Setup rules only after routes are Ok, so that route tables are
	# already populated when rule starts routing traffic to them.
	process_ipv4rules add
}

if iface_is_up $NAME; then
	case "$BOOTPROTO" in
		static)
			try_static && config_routes_rules
			;;
		dhcp)
			try_dhcp && config_routes_rules
			;;
		ipv4ll)
			try_ipv4ll && config_routes_rules
			;;
		dhcp-static)
			try_dhcp || try_static && config_routes_rules
			;;
		dhcp-ipv4ll)
			try_dhcp || try_ipv4ll && config_routes_rules
			;;
		dhcp-ipv4ll-static)
			try_dhcp || try_ipv4ll || try_static && config_routes_rules
			;;
		*)
			print_error "unknown BOOTPROTO '$BOOTPROTO'"
			;;
	esac
fi
