#!/bin/sh -u

cachedir="/var/cache/alterator/net-eth"

rdelim='[[:space:]]\+'
wdelim=' '

alterator_api_version=1

. alterator-sh-functions
. alterator-net-functions
. alterator-hw-functions
. shell-config
. shell-var

list_avail_ifaces()
{
	local iface=
	list_eth | while read iface; do
		if iface_has_host_with_cache "$cachedir" "$iface"; then
			continue
		fi

		echo "$iface"
	done
}

list_bridge_members()
{
	local name="$1"; shift
	local ifacedir="$(ifacedir_with_cache "$cachedir" "$name")"

	if [ -d "$ifacedir" -a "$(read_iface_option "$ifacedir" TYPE)" = "bri" ]; then
		for s in $(read_iface_host_var "$ifacedir"); do
			echo "$s"
		done
	fi
}

init_cache()
{
	local name="$1"; shift

	if [ -z "$name" ]; then
		return
	elif iface_will_removed "$cachedir" "$name"; then
		rm -r -- "$cachedir/$name/"
	elif [ -d "$cachedir/$name" ]; then
		return
	fi

	if [ -d "/etc/net/ifaces/$name" ]; then
		mkdir -p -- "$cachedir/"
		cp -a "/etc/net/ifaces/$name" "$cachedir/"
		return
	fi

	mkdir -p -- "$cachedir/$name"

	cat > "$cachedir/$name/options" <<OPTIONS_TEMPLATE
TYPE=bri
ONBOOT=yes
DISABLED=no
NM_CONTROLLED=no
CONFIG_WIRELESS=no
CONFIG_IPV4=yes
CONFIG_IPV6=no
BOOTPROTO=static
HOST=""
OPTIONS_TEMPLATE
}

on_message()
{
	case "$in_action" in

		list)
			case "${in__objects##*/}" in
				avail_ifaces) list_avail_ifaces | write_enum;;
			    bridge_members) list_bridge_members "$in_bridge" | write_enum;;
			esac
			;;
		read)
			case "$in__objects" in
				/)
					;;
				new_name)
					write_string_param "new_name" "$(next_iface_with_cache "$cachedir" br)"
					;;
			esac
			;;
		write)
			init_cache "$in_bridge"

			case "$in__objects" in
				/)
					;;
				rm_bridge)
					remove_host_iface_with_cache "$cachedir" "$in_bridge"
					;;
				add_iface)
					host_add_slaves_with_cache "$cachedir" "$in_bridge" "$in_name"
					;;
				del_iface)
					host_del_slaves_with_cache "$cachedir" "$in_bridge" "$in_name"
					;;
			esac
			;;
	esac
}

message_loop
