#!/bin/bash

CONFIG=/etc/default/opennebula-p2p-vxlan

set -e

if [ ! -e "${CONFIG}" ]; then
	echo "Missing configuration '${CONFIG}'" >&2
	exit 1
fi

source "${CONFIG}"

###

# delete VXLAN and bridge interfaces
function stop {
	for D in ${ONE_P2P_VXLAN_DEV} ${ONE_P2P_BRIDGE}; do
		if ip link show ${D} &>/dev/null; then
			ip link del dev ${D}
		fi
	done
}

# create VXLAN and bridge interfaces
function start {
	# create bridge
	ip link add name "${ONE_P2P_BRIDGE}" type bridge
	ip link set "${ONE_P2P_BRIDGE}" up

	# create VXLAN interface
	ip link add ${ONE_P2P_VXLAN_DEV} \
		type vxlan id ${ONE_P2P_VXLAN_VNI} \
		dev ${ONE_P2P_PHYDEV} \
		dstport 4789 \
		local ${ONE_P2P_VXLAN_LOCAL_IP}

	ip link set "${ONE_P2P_VXLAN_DEV}" up
	ip link set "${ONE_P2P_VXLAN_DEV}" master "${ONE_P2P_BRIDGE}"

	# add FDB entries
	refresh_fdb
}

function refresh_fdb {
	for R in ${ONE_P2P_REMOTES}; do
		if [ "${R}" = "${ONE_P2P_VXLAN_LOCAL_IP}" ]; then
			continue
		fi

		bridge fdb append 00:00:00:00:00:00 \
			dev "${ONE_P2P_VXLAN_DEV}" \
			dst "${R}"
	done

	# compare list of remotes in existing FDB entries
	# with list of required remotes from the configuration and
	# remove obsolete FDB entires
	local _REMOTES_LIVE=$(
		bridge fdb show dev "${ONE_P2P_VXLAN_DEV}" | \
			grep '^00:00:00:00:00:00 ' | \
			cut -d' ' -f3
	)

	for R_LIVE in ${_REMOTES_LIVE}; do
		for R_CONF in ${ONE_P2P_REMOTES}; do
			[ "${R_LIVE}" = "${ONE_P2P_VXLAN_LOCAL_IP}" ] && break
			[ "${R_LIVE}" = "${R_CONF}" ] && continue 2
		done

		bridge fdb del 00:00:00:00:00:00 \
			dev "${ONE_P2P_VXLAN_DEV}" \
			dst "${R_LIVE}"
	done
}

###

case $1 in
	start)
		start
		;;
	stop)
		stop
		;;
	reload)
		refresh_fdb
		;;
	*)
		if [ -z "${1}" ]; then
			echo "Syntax: $0 [start|stop|reload]"
		else
			echo "ERROR: Invalid command '${1}'" >&2
		fi

		exit 1
esac
