#!/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

###
get_ifacedir()
{
	local name="$1"; shift

	if [ -d "$cachedir/$name" ];then
	    echo "$cachedir/$name"
	else
	    echo "/etc/net/ifaces/$name"
	fi
}

# We can't use list_eth():
# it can show bridge instead of real interface
list_real_eth()
{
	netdev_list|
	while read iface; do
		netdev_is_eth "$iface" || continue
		netdev_is_real "$iface" || continue

		echo "$iface"
	done
}

# We can't use next_iface():
# we need look to the cachedir too,
# there can be not commited bond interfaces
next_bond_iface()
{
	local i=0
	local path1="/etc/net/iface/bond"
	local path2="$cachedir/bond"
	while true; do
		[ -d "$path1$i" -o -d "$path2$i" ] || { echo "bond$i" && break; }
		[ ! -f "$path2$i/REMOVED" ] || { echo "bond$i" && break; }
		i=$(($i + 1))
	done
}

init_slave_iface()
{
	local name="$1"; shift
	local is_wireless=

	if [ ! -d "$cachedir/$name" ]; then
		if [ -d "/etc/net/ifaces/$name" ]; then
			cp -a "/etc/net/ifaces/$name" "$cachedir/"
		else
			mkdir -p "$cachedir/$name"
			write_iface_option "$cachedir/$name" TYPE eth
			netdev_is_wireless "$name" && is_wireless=yes || is_wireless=no
			write_iface_option "$cachedir/$name" CONFIG_WIRELESS "$is_wireless"
		fi
	fi

	rm -f "$cachedir/$name/"ipv*address "$cachedir/$name/"ipv*route
	write_iface_option "$cachedir/$name" DISABLED no
	write_iface_option "$cachedir/$name" NM_CONTROLLED no
	write_iface_option "$cachedir/$name" BOOTPROTO static
	write_iface_option "$cachedir/$name" ONBOOT yes
	write_iface_option "$cachedir/$name" CONFIG_IPV4 no
	write_iface_option "$cachedir/$name" CONFIG_IPV6 no
}

iface_has_host_cached()
{
	local name="$1"; shift
	local i= exclude=

	if 	iface_has_host "$name" "$cachedir"; then
		return 0
	fi
	# don't check ifaces which were cached
	for i in $(find "$cachedir" -mindepth 1 -maxdepth 1 -type d); do
		exclude="$exclude${exclude:+ -o }-path /etc/net/ifaces/${i##*/}/options"
	done
	if [ -n "$exclude" ]; then
		exclude="\( \( $exclude \) -prune -o -print \)"
	fi
	for i in $(eval find /etc/net/ifaces -maxdepth 2 -mindepth 2 -name options $exclude); do
		if egrep -qs "^HOST=[\"']?([[:alnum:]]+[[:blank:]])*$name([[:blank:]][[:alnum:]]+)*[\"']?[[:blank:]]*$" $i; then
			return 0
		fi
	done

	return 1
}

list_avail_ifaces()
{
	local iface=
	list_real_eth | while read iface; do
		if iface_has_host_cached "$iface"; then
			continue
		fi

		echo "$iface"
	done
}

list_bonded_ifaces()
{
	local name="$1"; shift
	local ifacedir="$(get_ifacedir "$name")"

	if [ -d "$ifacedir" ]; then
		for s in $(read_iface_slaves "$ifacedir"); do
			echo "$s"
		done
	fi
}

read_bond_iface()
{
	local name="$1"; shift
	local ifacedir="$(get_ifacedir "$name")"
	local bond_options=

	[ -n "$name" -a -d "$ifacedir" ] || return

	write_string_param "mode" "$(read_iface_option "$ifacedir" BONDMODE)"

	bond_options="$(read_iface_option "$ifacedir" BONDOPTIONS)"
	shell_var_unquote bond_options "$bond_options"
	# Remove alone space in the options
	# (it was setted by us because etcnet not allow empty BONDOPTIONS)
	if [ "$bond_options" = ' ' ]; then
		bond_options=''
	fi
	# arp_ip_target value should be prepended with '+' in the config
	# Remove it during reading
	if [ -n "$bond_options" ]; then
		bond_options="$(printf "%s" "$bond_options" | sed -r 's|arp_ip_target=\+([[:digit:].]+)|arp_ip_target=\1|')"
	fi
	write_string_param "bond_options" "$bond_options"
}

write_bond_iface()
{
	local name="$1"; shift
	local ifacedir="$cachedir/$name"
	local bond_options="$in_bond_options"

	[ -n "$name" -a -d "$ifacedir" ] || return

	write_iface_option "$ifacedir" BONDMODE "$in_mode"
	if [ -n "$bond_options" ]; then
		# arp_ip_target value should be prepended with '+' in the config
		bond_options="$(printf "%s" "$bond_options" | sed -r 's|arp_ip_target=([[:digit:].]+)|arp_ip_target=+\1|')"
	else
		# Etcnet don't allow create bond with empty options.
		# But why not? Just set it to space.
		bond_options=" "
	fi
	write_iface_option "$ifacedir" BONDOPTIONS "\"$bond_options\""
}

bond_add_iface()
{
	local bond="$1"; shift
	local names="$1"; shift
	local ifacedir="$cachedir/$bond"
	local host= i= new_names=

	[ -n "$bond" -a "$names" -a -d "$ifacedir" ] || return

	host="$(read_iface_slaves "$ifacedir")"

	local IFS=';'
	for i in $names; do
		new_names="$new_names${new_names:+ }$i"
		init_slave_iface "$i"
	done

	if [ -n "$host" ]; then
		host="$host $new_names"
	else
		host="$new_names"
	fi

	write_iface_option "$ifacedir" HOST "\"$host\""
}

bond_del_iface()
{
	local bond="$1"; shift
	local names="$1"; shift
	local ifacedir="$cachedir/$bond"
	local i=

	[ -n "$bond" -a "$names" -a -f "$ifacedir/options" ] || return

	local IFS=';'
	for i in $names; do
		sed -i -r "/^HOST=/{s/$i//; s/ +/ /; s/=([\"'])? /=\1/; s/ ([\"'])?$/\1/}" "$ifacedir/options"
		if [ ! -d "$cachedir/$i" ]; then
			cp -a "/etc/net/ifaces/$i" "$cachedir/"
		fi
		write_iface_option "$cachedir/$i" CONFIG_IPV4 yes
	done
}

remove_bond()
{
	local bond="$1"; shift
	local ifacedir="$cachedir/$bond"
	local host=

	[ -d "$ifacedir" -a ! -f "$ifacedir/REMOVED" ] || return

	host="$(read_iface_slaves "$ifacedir" | tr ' ' ';')"
	bond_del_iface "$bond" "$host"

	rm -f -- "$ifacedir"/*
	if [ -d "/etc/net/ifaces/$bond" ]; then
		touch "$ifacedir/REMOVED"
	else
		rmdir -- "$ifacedir"
	fi
}

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

	if [ -z "$name" ]; then
		return
	elif [ -f "$cachedir/$name/REMOVED" ]; 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=bond
ONBOOT=yes
DISABLED=no
NM_CONTROLLED=no
CONFIG_WIRELESS=no
CONFIG_IPV4=yes
CONFIG_IPV6=no
BOOTPROTO=static
HOST=""
BONDMODE=0
BONDOPTIONS=" "
OPTIONS_TEMPLATE
}

on_message()
{
	case "$in_action" in

		list)
			case "${in__objects##*/}" in
				avail_ifaces) list_avail_ifaces | write_enum;;
			    bonded_ifaces) list_bonded_ifaces "$in_bond" | write_enum;;
			esac
			;;
		read)
			case "$in__objects" in
				/)
					read_bond_iface "$in_bond"
					;;
				new_name)
					write_string_param "new_name" "$(next_bond_iface)"
					;;
			esac
			;;
		write)
			init_cache "$in_bond"

			case "$in__objects" in
				/)
					write_bond_iface "$in_bond"
					;;
				rm_bond)
					remove_bond "$in_bond"
					;;
				add_iface)
					bond_add_iface "$in_bond" "$in_name"
					;;
				del_iface)
					bond_del_iface "$in_bond" "$in_name"
					;;
			esac
			;;
	esac
}

message_loop
