#!/bin/sh

set -e
#set -x

ME=$(basename $0)
MODE=""

usage () {
	echo "Usage: ${ME} --mode ovs|ovn"
	echo "  --mode  Networking mode: ovs or ovn (mandatory)."
}

while [ $# -gt 0 ] ; do
	case "$1" in
	--mode)
		if [ $# -lt 2 ] ; then
			echo "Option --mode requires an argument (ovs or ovn)."
			exit 1
		fi
		MODE="$2"
		shift
		;;
	*)
		usage
		exit 1
		;;
	esac
	shift
done
if [ -z "${MODE}" ] ; then
	usage
	exit 1
fi
if [ "${MODE}" != "ovs" ] && [ "${MODE}" != "ovn" ] ; then
	echo "Invalid mode '${MODE}' (expected ovs or ovn)."
	exit 1
fi

. /root/oci-openrc

DEBIAN_RELEASE=$(lsb_release -c -s)
DEBIAN_RELEASE_NUM=$(lsb_release -r -s)

if ! [ -r /etc/oci-poc/oci-poc.conf ] ; then
	echo "Cannot read /etc/oci-poc/oci-poc.conf: exiting."
	exit 1
fi
# The user-owned values (GUESTS_DOMAIN_NAME, OCI_VM_ROOT_PASS,
# PRIMARY_DNS, SECONDA_DNS, REPO_TOKEN_DEBIAN_MIRROR_HOST) are sourced
# BEFORE the stock configuration file, so that the derived variables
# of oci-poc.conf are evaluated with them. They live only in the
# local file, which is mandatory: it is sourced first, and the
# scripts refuse to run without it.
if [ -r /etc/oci-poc/oci-poc-local.conf ] ; then
	. /etc/oci-poc/oci-poc-local.conf
else
	echo "Cannot read /etc/oci-poc/oci-poc-local.conf: exiting."
	exit 1
fi
. /etc/oci-poc/oci-poc.conf

##################
### NETWORKING ###
##################
oci_poc_prov_cloud_provision_bgp_dynamic_routing () {
	echo "===> Provisionning BGP networking"
	echo "-> Create BGP peers"
	if [ ""$(openstack bgp peer list  --format csv | q -H -d, "SELECT Name FROM - WHERE Name='leaf1'") = "leaf1" ] ; then
		echo 'leaf1 already created'
	else
		openstack bgp peer create --peer-ip ${BGP_NET_LEAF1_PEER_IP} --remote-as ${BGP_NET_LEAF_1_REMOTE_AS} leaf1
	fi
	if [ ""$(openstack bgp peer list  --format csv | q -H -d, "SELECT Name FROM - WHERE Name='leaf2'") = "leaf2" ] ; then
		echo 'leaf1 already created'
	else
		openstack bgp peer create --peer-ip ${BGP_NET_LEAF2_PEER_IP} --remote-as ${BGP_NET_LEAF_2_REMOTE_AS} leaf2
	fi

	echo "-> Create spearkers"
	# First speaker is for IPv4, 2nd one is for v6
	if [ ""$(openstack bgp speaker list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='speaker-leaf1'") = "speaker-leaf1" ] ; then
		echo "speaker-leaf1 already created"
	else
		openstack bgp speaker create --local-as ${BGP_NET_SPEAKER_LOCAL_AS} --ip-version 6 --no-advertise-floating-ip-host-routes speaker-leaf1
	fi
	if [ ""$(openstack bgp speaker list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='speaker-leaf2'") = "speaker-leaf2" ] ; then
		echo "speaker-leaf2 already created"
	else
		openstack bgp speaker create --local-as ${BGP_NET_SPEAKER_LOCAL_AS} --ip-version 4 --no-advertise-floating-ip-host-routes speaker-leaf2
	fi

	echo "-> Add peers to BGP spearker"
	if [ ""$(openstack bgp speaker show speaker-leaf1 --format value -c peers) = "[]" ] ; then
		echo "adding leaf1 as peer to speaker-leaf1"
		openstack bgp speaker add peer speaker-leaf1 leaf1
	else
		echo "leaf1 already added as peer to speaker-leaf1"
	fi
	if [ ""$(openstack bgp speaker show speaker-leaf2 --format value -c peers) = "[]" ] ; then
		echo "adding leaf2 as peer to speaker-leaf2"
		openstack bgp speaker add peer speaker-leaf2 leaf2
	else
		echo "leaf2 already added as peer to speaker-leaf2"
	fi

	echo "-> Fetching BGP network agent ID for cl1-network-1"
	BGP_AGENT_NODE_1=$(openstack network agent list --agent-type bgp --host cl1-network-1.infomaniak.ch --format value -c ID)
	BGP_AGENT_NODE_2=$(openstack network agent list --agent-type bgp --host cl1-network-2.infomaniak.ch --format value -c ID)

	echo "-> Adding spearker to BGP dragent of network node 1"
	if [ ""$(openstack bgp dragent list --bgp-speaker speaker-leaf2 --format value -c Host 2>/dev/null) = "" ] ; then
		openstack bgp dragent add speaker ${BGP_AGENT_NODE_1} speaker-leaf2 || true
	fi
	if [ ""$(openstack bgp dragent list --bgp-speaker speaker-leaf1 --format value -c Host 2>/dev/null) = "" ] ; then
		openstack bgp dragent add speaker ${BGP_AGENT_NODE_2} speaker-leaf1 || true
	fi
}

oci_poc_prov_cloud_create_networks_ext_net1 () {
	echo "===> Creating networking for ext-net1 dual-stack, direct-attached to VMs"

	# With the OVN mode, there is no transport network: the fabric
	# connectivity rides the management and chassis BGP sessions, and
	# the ovn-bgp service plugin needs no flat underlay. The address
	# scopes, the subnet pools and ext-provider1 exist for the OVS
	# mode only, whose BGP speakers and network nodes live on them.
	if [ "${MODE}" != "ovn" ] ; then
		echo "-> Creating address scopes"
		if [ ""$(openstack address scope list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-bgp4'") = "ext-bgp4" ] ; then
			echo "Address scope ext-bgp4 already exists."
		else
			openstack address scope create --ip-version 4 ext-bgp4
		fi
		if [ ""$(openstack address scope list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-bgp6'") = "ext-bgp6" ] ; then
			echo "Address scope ext-bgp6 already exists."
		else
			openstack address scope create --ip-version 6 ext-bgp6
		fi

		echo "-> Creating the IPv4 transport subnet pool"
		if [ ""$(openstack subnet pool list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='poolv4-provider1'") = "poolv4-provider1" ] ; then
			echo "Subnetpool poolv4-provider1 already created"
		else
			openstack subnet pool create --pool-prefix ${BGP_NET_TRANSPORT_IPV4}.0/24 --address-scope ext-bgp4 --default-prefix-length 24 --max-prefix-length 24 --min-prefix-length 24 poolv4-provider1
		fi

		# The IPv6 transport subnet draws from poolv6-shared1: a
		# transport /64 inside the program envelope can never be a
		# scope-carrying pool of its own (neutron 409s on the
		# overlapping prefixes), and the dynamic routing scope model
		# needs the ext-gw carrier's v6 subnet to be scoped, or the
		# IPv6 speaker derives no address scope and advertises nothing.
		echo "-> Creating the direct attach IPv4 subnet pool"
		if [ ""$(openstack subnet pool list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='poolv4-shared1'") = "poolv4-shared1" ] ; then
			echo "Subnetpool poolv4-shared1 already created"
		else
			openstack subnet pool create --pool-prefix ${EXT_NET1_SUBNET_PREFIX}.0/24 --address-scope ext-bgp4 --default-prefix-length 24 --max-prefix-length 24 --min-prefix-length 24 poolv4-shared1
		fi

		echo "-> Creating the direct attach IPv6 subnet pool"
		if [ ""$(openstack subnet pool list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='poolv6-shared1'") = "poolv6-shared1" ] ; then
			echo "Subnetpool poolv6-shared1 already created"
		else
			openstack subnet pool create --pool-prefix ${EXT_NET1_IPV6}/56 --address-scope ext-bgp6 --default-prefix-length 64 --max-prefix-length 64 --min-prefix-length 64 poolv6-shared1
		fi

		echo "-> Creating the ext-provider1 network"
		if [ ""$(openstack network list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-provider1'") = "ext-provider1" ] ; then
			echo "ext-provider1 already created"
		else
			openstack network create --description "Transport network for public ranges" --external --provider-network-type vlan --provider-physical-network external --provider-segment ${BGP_NET_TRANSPORT_VLAN} ext-provider1
		fi

		echo "-> Creating the ext-provider1-v4subnet1"
		if [ ""$(openstack subnet list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-provider1-v4subnet1'") = "ext-provider1-v4subnet1" ] ; then
			echo "ext-provider1-v4subnet1 already created"
		else
			openstack subnet create --subnet-pool poolv4-provider1 --subnet-range ${BGP_NET_TRANSPORT_IPV4}.0/24 --gateway ${BGP_NET_TRANSPORT_IPV4}.1 --network  ext-provider1 --allocation-pool start=${BGP_NET_TRANSPORT_IPV4}.2,end=${BGP_NET_TRANSPORT_IPV4}.252 ext-provider1-v4subnet1
		fi

		echo "-> Creating the ext-provider1-v6subnet1"
		if [ ""$(openstack subnet list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-provider1-v6subnet1'") = "ext-provider1-v6subnet1" ] ; then
			echo "ext-provider1-v6subnet1 already created"
		else
			openstack subnet create --ip-version 6 --subnet-pool poolv6-shared1 --subnet-range ${BGP_NET_TRANSPORT_IPV6}/64 --gateway ${BGP_NET_TRANSPORT_IPV6}1 --network ext-provider1 --allocation-pool start=${BGP_NET_TRANSPORT_IPV6}4,end=${BGP_NET_TRANSPORT_IPV6}ffff:ffff:ffff --ipv6-ra-mode dhcpv6-stateful --ipv6-address-mode dhcpv6-stateful ext-provider1-v6subnet1
		fi
	fi

	echo "-> Creating ext-net1"
	if [ ""$(openstack network list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-net1'") = "ext-net1" ] ; then
		echo "ext-net1 already created"
	else
		openstack network create --share --description "Public shared network" ext-net1
	fi

	echo "-> Creating ext-net1-v4subnet1"
	if [ ""$(openstack subnet list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-net1-v4subnet1'") = "ext-net1-v4subnet1" ] ; then
		echo "ext-net1-v4subnet1 already created"
	elif [ "${MODE}" = "ovn" ] ; then
		# No subnet pool in the OVN mode: the router-less provisioning
		# carries no pools, and the fixed ranges need no allocation
		# policy.
		openstack subnet create --description "Public shared IPv4 subnet" --subnet-range ${EXT_NET1_SUBNET_PREFIX}.0/24 --gateway auto --network ext-net1 --allocation-pool start=${EXT_NET1_SUBNET_PREFIX}.2,end=${EXT_NET1_SUBNET_PREFIX}.254 --dns-nameserver ${PRIMARY_DNS} --dns-nameserver ${SECONDA_DNS} ext-net1-v4subnet1
	else
		openstack subnet create --description "Public shared IPv4 subnet" --subnet-pool poolv4-shared1 --subnet-range ${EXT_NET1_SUBNET_PREFIX}.0/24 --gateway auto --network ext-net1 --allocation-pool start=${EXT_NET1_SUBNET_PREFIX}.2,end=${EXT_NET1_SUBNET_PREFIX}.254 --dns-nameserver ${PRIMARY_DNS} --dns-nameserver ${SECONDA_DNS} ext-net1-v4subnet1
	fi

	echo "-> Creating ext-net1-v6subnet1"
	if [ ""$(openstack subnet list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-net1-v6subnet1'") = "ext-net1-v6subnet1" ] ; then
		echo "ext-net1-v6subnet1 already created"
	elif [ "${MODE}" = "ovn" ] ; then
		openstack subnet create --ip-version 6 --description "Public shared IPv6 subnet" --subnet-range ${EXT_NET1_IPV6}/64 --gateway ${EXT_NET1_IPV6}1 --network ext-net1 --dns-nameserver ${PRIMARY_DNS6} --dns-nameserver ${SECONDA_DNS6} --ipv6-ra-mode dhcpv6-stateful --ipv6-address-mode dhcpv6-stateful ext-net1-v6subnet1
	else
		openstack subnet create --ip-version 6 --description "Public shared IPv6 subnet" --subnet-pool poolv6-shared1 --subnet-range ${EXT_NET1_IPV6}/64 --gateway ${EXT_NET1_IPV6}1 --network ext-net1 --dns-nameserver ${PRIMARY_DNS6} --dns-nameserver ${SECONDA_DNS6} --ipv6-ra-mode dhcpv6-stateful --ipv6-address-mode dhcpv6-stateful ext-net1-v6subnet1
	fi

	# With the OVN mode, ext-net1 goes router-less: the ovn-bgp
	# service plugin owns the subnet's gateway IP as an anycast
	# gateway on the BGP main router (leak-routes below), so a router
	# interface on the subnets would conflict with it. The OVS mode
	# keeps the HA router, gatewayed on ext-provider1.
	if [ "${MODE}" != "ovn" ] ; then
		echo "-> Creating router ext-net1-router1"
		if [ ""$(openstack router list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-net1-router1'") = "ext-net1-router1" ] ; then
			echo "Router ext-net1-router1 already exists"
		else
			openstack router create --description "Router for public shared network" --ha ext-net1-router1
		fi

		echo "-> Setting ext-net1-router1 external gateway"
		if [ ""$(openstack router show ext-net1-router1 --format json -c external_gateway_info | jq '.["external_gateway_info"]' -r) = "null" ] ; then
			openstack router set --external-gateway ext-provider1 ext-net1-router1
		else
			echo "External gateway ext-provider1 already set in ext-net1-router1"
		fi

		echo "-> Adding ext-net1-v4subnet1 and ext-net1-v6subnet1 subnets to ext-net1-router1"
# The test below does not work. Not sure how to get it fixed.
# In the mean time, lets just do || true, always.
#	ROUTER_SHOW=$(openstack router show ext-net1-router1 --format json -c interfaces_info | jq '.["interfaces_info"]' -r)
#	if [ "${ROUTER_SHOW}" = '[]' ] ; then
#		openstack router add subnet ext-net1-router1 ext-net1-v4subnet1
#		openstack router add subnet ext-net1-router1 ext-net1-v6subnet1
#	else
#		echo "Subnet already there"
#	fi
		openstack router add subnet ext-net1-router1 ext-net1-v4subnet1 || true
		openstack router add subnet ext-net1-router1 ext-net1-v6subnet1 || true
	fi

	# With the OVN mode, the ovn-bgp service plugin only announces a
	# shared network's subnets into the underlay when leak_routes is
	# set on them: the subnet's gateway IP becomes an anycast gateway
	# owned by the BGP main router, and the network's used IPs are
	# advertised as /32 host routes. This is what replaces the legacy
	# "bgp speaker add network" calls below, and the router block
	# above.
	if [ "${MODE}" = "ovn" ] ; then
		openstack subnet set --leak-routes ext-net1-v4subnet1
		openstack subnet set --leak-routes ext-net1-v6subnet1
	fi

	# With the OVN mode, there is no dynamic routing speaker API: the
	# ovn-bgp service plugin announces the provider network's ports
	# itself, and there is no speaker to add networks to.
	if [ "${MODE}" != "ovn" ] ; then
		echo "-> Adding ext-provider1 to speaker-leaf1"
		if [ ""$(openstack bgp speaker show speaker-leaf1 --format value -c networks) = "[]" ] ; then
			openstack bgp speaker add network speaker-leaf1 ext-provider1
		else
			echo "Network ext-provider1 already added to speaker-leaf1"
		fi

		echo "-> Adding ext-provider1 to speaker-leaf2"
		if [ ""$(openstack bgp speaker show speaker-leaf2 --format value -c networks) = "[]" ] ; then
			openstack bgp speaker add network speaker-leaf2 ext-provider1
		else
			echo "Network ext-provider1 already added to speaker-leaf2"
		fi
	fi
}

oci_poc_prov_cloud_create_networks_floating_ips () {
	echo "===> Creating networking for ext-floating1 IPv4 only."
	echo "-> Creating the ext-floating1 network"
	if [ ""$(openstack network list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-floating1'") = "ext-floating1" ] ; then
		echo "ext-floating1 already created"
	elif [ "${MODE}" = "ovn" ] ; then
		# Floating IPs need no L2 in the OVN mode: the
		# ovn-bgp service plugin redistributes NAT routes
		# as host routes.
		openstack network create --description "Floating IPs provider network" --external --provider-network-type geneve ext-floating1
	else
		openstack network create --description "Floating IPs provider network" --external --provider-network-type vlan --provider-physical-network external --provider-segment ${FLOATING_IP_SUBNET_VLAN} ext-floating1
	fi

	echo "-> Creating the ext-floating1-v4subnet network"
	if [ ""$(openstack subnet list --format csv | q -H -d, "SELECT Name FROM - WHERE Name='ext-floating1-v4subnet'") = "ext-floating1-v4subnet" ] ; then
		echo "ext-floating1-v4subnet already created"
	else
		openstack subnet create --subnet-range ${FLOATING_IP_SUBNET_PREFIX}.0/24 --gateway auto --network ext-floating1 --allocation-pool start=${FLOATING_IP_SUBNET_PREFIX}.2,end=${FLOATING_IP_SUBNET_PREFIX}.252 --dns-nameserver ${PRIMARY_DNS} --dns-nameserver ${SECONDA_DNS} ext-floating1-v4subnet1
	fi

	# With the OVN mode, leaking ext-floating1 into the underlay makes
	# the subnet's gateway IP an anycast gateway owned by the BGP main
	# router, and announces tenant routers' SNAT external gateway ports
	# as /32 host routes. Without it, a tenant router with enable_snat
	# on ext-floating1 has a default route pointing at an IP that
	# nobody answers, and its egress is dead. Floating IPs keep working
	# either way: the plugin still redistributes their NAT routes.
	if [ "${MODE}" = "ovn" ] ; then
		openstack subnet set --leak-routes ext-floating1-v4subnet1
	fi
}

# With the OVN mode, BGP-2-the-host is handled by the ovn-bgp service
# plugin of Neutron, and the dynamic routing speaker API isn't used:
# FRR on the compute nodes does the actual peering and announcing.
if [ "${MODE}" != "ovn" ] ; then
	oci_poc_prov_cloud_provision_bgp_dynamic_routing
fi
oci_poc_prov_cloud_create_networks_ext_net1
oci_poc_prov_cloud_create_networks_floating_ips

exit 0
