#!/bin/sh -u

PATH="$PATH:/sbin"

. shell-config
. alterator-net-functions

DATADIR="$1"; shift
ETCNET_IFACES_DIR=/etc/net/ifaces

[ -n "$DATADIR" -a -f "$DATADIR"/neteth_data ] || \
	fatal "Couldn't find data file in $DATADIR"

_neteth_exit_handler()
{
	local rc=$?
	trap - EXIT
	[ -z "$TMP_IFACES_DIR" ] ||
		rm -rf -- "$TMP_IFACES_DIR"
	exit $rc
}

trap _neteth_exit_handler HUP INT QUIT TERM EXIT
TMP_IFACES_DIR="$(mktemp -d --tmpdir amm-neteth-tmp-ifaces-dirXXXXXXXX)"

ifaces_list="$(shell_config_get "$DATADIR"/neteth_data neteth_ifaces_list)"

for iface in $ifaces_list; do
	mkdir -p "$TMP_IFACES_DIR/$iface"

	for addr in $(shell_config_get "$DATADIR"/neteth_data neteth_iface_addresses_$iface); do
		write_iface_addr "$TMP_IFACES_DIR/$iface" "$addr" 4 || exit 1
	done

	tmp="$(shell_config_get "$DATADIR"/neteth_data neteth_iface_search_$iface)"
	if [ -n "$tmp" ]; then
		write_iface_search "$TMP_IFACES_DIR/$iface" "$tmp" || exit 1
	fi
	tmp="$(shell_config_get "$DATADIR"/neteth_data neteth_iface_dns_$iface)"
	if [ -n "$tmp" ]; then
		write_iface_dns "$TMP_IFACES_DIR/$iface" "$tmp" || exit 1
	fi

	tmp="$(shell_config_get "$DATADIR"/neteth_data neteth_iface_configuration_$iface)"
	if [ -n "$tmp" ]; then
		[ ! -s "$ETCNET_IFACES_DIR/$iface/options" ] ||
			cp "$ETCNET_IFACES_DIR/$iface/options" "$TMP_IFACES_DIR/$iface"
		write_iface_option "$TMP_IFACES_DIR/$iface" BOOTPROTO "$tmp" || exit 1
	fi
	
	tmp="$(shell_config_get "$DATADIR"/neteth_data neteth_iface_default_gw_$iface)"
	if [ -n "$tmp" ]; then
		[ ! -s "$ETCNET_IFACES_DIR/$iface/ipv4route" ] ||
			cp "$ETCNET_IFACES_DIR/$iface/ipv4route" "$TMP_IFACES_DIR/$iface"
		write_iface_default_gw "$TMP_IFACES_DIR/$iface" "$tmp" 4 || exit 1
	fi

	[ -d "$ETCNET_IFACES_DIR/$iface" ] || mkdir -p "$ETCNET_IFACES_DIR/$iface/"
	for f in $(find "$TMP_IFACES_DIR/$iface" -mindepth 1 -maxdepth 1 -type f); do
		mv -f "$f" "$ETCNET_IFACES_DIR/$iface/" || exit 1
	done
done

rm -rf -- "$TMP_IFACES_DIR"
trap - HUP INT QUIT TERM EXIT

# reset ifaces
for iface in $ifaces_list; do
	ifdown "$iface"
	ifup "$iface"
done

exit 0
