#!/bin/bash

DEFAULT_IF=$(route -n | awk '/^0.0.0.0/{print $NF; exit}')
DEFAULT_IP=$(ip address show $DEFAULT_IF|awk 'match($0,/inet .*\//){print substr($0, RSTART+5, RLENGTH-6)}')

UNDERLAY="$(echo $DEFAULT_IP|cut -d. -f1-2).0.0/16"
OVERLAY="250.0.0.0/8"

function Abort()
{
	echo "FAIL: $*" >&2
	exit 1
}

storage_list()
{
	lxc storage list 2>/dev/null | awk '
		FNR>3 && /^\|/{
			split($0, A, " ?| ?")
			print A[2]
		}
	'
}

lxd waitready || Abort "Failed to bring LXD online"

if [ "$(storage_list)" = "" ]; then
	echo "II: Auto-init LXD..."
	lxd init --auto 2>&1 || Abort "Error during LXD init"
fi

[ -n "${http_proxy}" ] && lxc config set core.proxy_http "${http_proxy}"
[ -n "${https_proxy}" ] && lxc config set core.proxy_https "${https_proxy}"

if [ "$(fanctl show | grep ^fan-)" = "" ]; then
	echo "II: Creating Fan Bridge..."
	fanatic enable-fan -u $UNDERLAY -o $OVERLAY ||
		Abort "Error on enable-fan"
fi
FAN_BRIDGE="$(brctl show | awk '/fan-[0-9]/{print $1}')"
if [ "$FAN_BRIDGE" = "" ]; then
	Abort "There seems to be no Fan Bridge"
fi

if [ "$(lxc profile list 2>/dev/null | grep fan-)" = "" ]; then
	echo "II: Create LXD profile for Fan Bridge..."
	fanatic enable-lxd -u $UNDERLAY -o $OVERLAY ||
		Abort "Error on enable-lxd"
fi

echo "II: Test LXD..."
fanatic test-local-lxd -u $UNDERLAY -o $OVERLAY || Abort "Error on LXD test"

echo "II: Undefining LXD profile for Fan Bridge..."
fanatic disable-lxd -u $UNDERLAY -o $OVERLAY || Abort "Error on disable-lxd"

ifconfig $FAN_BRIDGE || Abort "No $FAN_BRIDGE left after disable-lxd"

echo "II: Removing Fan Bridge..."
fanatic disable-fan  -u $UNDERLAY -o $OVERLAY || Abort "Error on disable-fan"

echo "PASS"

exit 0
