#!/bin/bash

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

http_proxy=""
https_proxy=""
if echo "" | nc -w 2 squid.internal 3128 >/dev/null 2>&1; then
	INFO="Running in the Canonical CI environment"
	http_proxy="http://squid.internal:3128"
	https_proxy="https://squid.internal:3128"
elif echo "" | nc -w 2 10.245.64.1 3128 >/dev/null 2>&1; then
	INFO="Running in the Canonical enablement environment"
	http_proxy="http://10.245.64.1:3128"
	https_proxy="https://10.245.64.1:3128"
elif echo "" | nc -w 2 91.189.89.216 3128 >/dev/null 2>&1; then
	INFO="Running in the Canonical enablement environment"
	http_proxy="http://91.189.89.216:3128"
	https_proxy="https://91.189.89.216:3128"
fi
export http_proxy
export https_proxy

URI="http://index.docker.io/v1/repositories/library/ubuntu/images"
if wget -q -O/dev/null $URI; then
	echo $INFO
else
	unset http_proxy
	unset https_proxy
fi

if [ -n "$http_proxy" ]; then
	if [ ! -d /etc/systemd/system/docker.service.d ]; then
		mkdir /etc/systemd/system/docker.service.d
	fi
	echo -ne "[Service]\nEnvironment=\"HTTP_PROXY=$http_proxy\"\n" \
		>/etc/systemd/system/docker.service.d/http-proxy.conf
	systemctl daemon-reload
	systemctl restart docker.service
fi

echo "II: Auto-create Fan Bridge..."
echo -e '\n\n' | fanatic enable-fan || Abort "error on enable-fan"

FAN_BRIDGE=$(brctl show | awk '/fan-[0-9]/{print $1}')
if [ "$FAN_BRIDGE" = "" ]; then
	Abort "there seems to be no Fan Bridge"
fi

echo "II: Create docker Fan Network..."
echo -e '\n\n' | fanatic enable-docker || Abort "error on enable-docker"

echo "II: Test docker..."
echo -e '\n\n' | fanatic test-local-docker || Abort "error on docker test"

echo "II: Undefining docker Fan Network..."
echo -e '\n\n' | fanatic disable-docker || Abort "error on disable-docker"

ifconfig $FAN_BRIDGE || Abort "disable docker deconfigured $FAN_BRIDGE"

echo "II: Removing Fan Bridge..."
echo -e '\n\n' | fanatic disable-fan

echo "PASS"

exit 0
