#!/bin/sh

set -e

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

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

if ! [ -r /root/oci-openrc ] ; then
	echo "Cannot load /root/oci-openrc: exiting."
	exit 1
fi
if ! [ -r /root/octavia-openrc ] ; then
	echo "Cannot load /root/octavia-openrc: exiting."
	exit 1
fi
. /root/oci-openrc

oci_poc_prov_cloud_create_networks_internal_octavia () {
	SERVICE_PROJECT_ID=$(openstack project show services --format value -c id)

	# With the OVS mode, the octavia services reach the amphorae
	# through a dedicated transport network, VLAN-mounted on the 4th
	# pool subnet and announced to the fabric by the BGP speakers.
	# With the OVN mode, none of this is needed: the amphora
	# management subnet goes router-less, its gateway IP becoming an
	# anycast gateway on the BGP main router through the leak-routes
	# call below, just like ext-net1.
	if [ "${MODE}" != "ovn" ] ; then
		echo "-> Provisionning poolv4-provider2 as transport (connected) network for Octavia"
		OCTAVIA_PROVIDER_CONNECTED_POOL=$(openstack subnet pool list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='poolv4-provider2'")
		if [ -z "${OCTAVIA_PROVIDER_CONNECTED_POOL}" ] ; then
			openstack subnet pool create --pool-prefix ${OCTAVIA_TRANSPORT_NETWORK_SUBNET_PREFIX}.0/24 --address-scope ext-bgp4 --default-prefix-length 24 --max-prefix-length 24 --min-prefix-length 24 poolv4-provider2
		else
			echo "poolv4-provider2 (for Octavia) already provisionned."
		fi

		echo "-> Creating transport network for Octavia"
		OCTAVIA_TRANSPORT_NETWORK=$(openstack network list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='int-provider1'")
		if [ -z "${OCTAVIA_TRANSPORT_NETWORK}" ] ; then
			openstack network create --description "Transport network for Octavia LoadBalancer" --provider-network-type vlan --provider-physical-network external --provider-segment ${OCTAVIA_NETWORK_SUBNET_LAN} int-provider1
		else
			echo "int-provider1 already created"
		fi
		OCTAVIA_TRANSPORT_NETWORK=$(openstack network list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='int-provider1'")

		echo "-> Creating transport network subnet for Octavia"
		OCTAVIA_TRANSPORT_SUBNET=$(openstack subnet list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='int-provider1-subnet1'")
		if [ -z "${OCTAVIA_TRANSPORT_SUBNET}" ] ; then
			openstack subnet create --subnet-pool poolv4-provider2 --subnet-range ${OCTAVIA_TRANSPORT_NETWORK_SUBNET_PREFIX}.0/24 --gateway ${OCTAVIA_TRANSPORT_NETWORK_SUBNET_PREFIX}.1 \
				--network int-provider1 --allocation-pool start=${OCTAVIA_TRANSPORT_NETWORK_SUBNET_PREFIX}.2,end=${OCTAVIA_TRANSPORT_NETWORK_SUBNET_PREFIX}.252 int-provider1-subnet1
		else
			echo "int-provider1-subnet1 already created"
		fi

		echo "-> Creating RBAC for Octavia to access the int-provider1 network from the services project"
		RBAC_ID=$(openstack network rbac list --long --format csv | q -H -d, "SELECT ID FROM - WHERE "'`Object ID`'"='${OCTAVIA_TRANSPORT_NETWORK}'")
		if [ -z "${RBAC_ID}" ] ; then
			openstack network rbac create --type network --action access_as_external --target-project ${SERVICE_PROJECT_ID} ${OCTAVIA_TRANSPORT_NETWORK}
		else
			echo "RBAC for network int-provider1 already created"
		fi
	fi

	# The amphora subnet comes from a subnet pool in the OVS mode,
	# scoped to the ext-bgp4 address scope and shared to the services
	# project through RBACs. The OVN mode needs none of that plumbing:
	# the subnet is created directly from its fixed range below.
	if [ "${MODE}" != "ovn" ] ; then
		echo "-> Provisionning poolv4-octavia1 as BGP transported network for Octavia"
		OCTAVIA_BGP_TRANSPORTED_POOL=$(openstack subnet pool list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='poolv4-octavia1'")
		if [ -z "${OCTAVIA_BGP_TRANSPORTED_POOL}" ] ; then
			openstack subnet pool create --pool-prefix ${OCTAVIA_MGMT_NET_PREFIX}.0/24 --address-scope ext-bgp4 --default-prefix-length 24 --max-prefix-length 24 --min-prefix-length 24 poolv4-octavia1
		else
			echo "poolv4-octavia1 already created"
		fi
		OCTAVIA_BGP_TRANSPORTED_POOL=$(openstack subnet pool list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='poolv4-octavia1'")

		echo "-> Creating RBAC for Octavia to access ext-bgp4 address scope"
		ADDRESS_SCOPE_ID=$(openstack address scope list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='ext-bgp4'")
		RBAC_ID=$(openstack network rbac list --long --format csv | q -H -d, "SELECT ID FROM - WHERE "'`Object ID`'"='${ADDRESS_SCOPE_ID}'")
		if [ -z "${RBAC_ID}" ] ; then
			openstack network rbac create --type address_scope --action access_as_shared --target-project ${SERVICE_PROJECT_ID} ${ADDRESS_SCOPE_ID}
		else
			echo "RBAC already for address scope ext-bgp4 created"
		fi

		echo "-> Creating RBAC for Octavia to access poolv4-octavia1 subnet pool from the service project"
		RBAC_ID=$(openstack network rbac list --long --format csv | q -H -d, "SELECT ID FROM - WHERE "'`Object ID`'"='${OCTAVIA_BGP_TRANSPORTED_POOL}'")
		if [ -z "${RBAC_ID}" ] ; then
			openstack network rbac create --type subnetpool --action access_as_shared --target-project ${SERVICE_PROJECT_ID} ${OCTAVIA_BGP_TRANSPORTED_POOL}
		else
			echo "RBAC for subnetpool poolv4-octavia1 already created"
		fi
	fi

	. /root/octavia-openrc

	echo "-> Creating octavia internal network int-octavia1"
	OCTAVIA_INT_NETWORK=$(openstack network list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='int-octavia1'")
	if [ -z "${OCTAVIA_INT_NETWORK}" ] ; then
		openstack network create --description "Octavia LoadBalancer internal network" int-octavia1
	else
		echo "int-octavia1 network already created"
	fi

	echo "-> Creating octavia internal network subnet int-octavia1-subnet1"
	OCTAVIA_INT_SUBNET=$(openstack subnet list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='int-octavia1-subnet1'")
	if [ -z "${OCTAVIA_INT_SUBNET}" ] ; then
		if [ "${MODE}" = "ovn" ] ; then
			openstack subnet create --description "Octavia LoadBalancer amphora subnet" \
				--subnet-range ${OCTAVIA_MGMT_NET_PREFIX}.0/24 --gateway auto --network int-octavia1 \
				--allocation-pool start=${OCTAVIA_MGMT_NET_PREFIX}.2,end=${OCTAVIA_MGMT_NET_PREFIX}.254 \
				--dns-nameserver ${PRIMARY_DNS} --dns-nameserver ${SECONDA_DNS} int-octavia1-subnet1
		else
			openstack subnet create --description "Octavia LoadBalancer amphora subnet" --subnet-pool poolv4-octavia1 \
				--subnet-range ${OCTAVIA_MGMT_NET_PREFIX}.0/24 --gateway auto --network int-octavia1 \
				--allocation-pool start=${OCTAVIA_MGMT_NET_PREFIX}.2,end=${OCTAVIA_MGMT_NET_PREFIX}.254 \
				--dns-nameserver ${PRIMARY_DNS} --dns-nameserver ${SECONDA_DNS} int-octavia1-subnet1
		fi
	else
		echo "int-octavia1-subnet1 already created"
	fi
	OCTAVIA_INT_SUBNET=$(openstack subnet list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='int-octavia1-subnet1'")

	# With the OVN mode, int-octavia1 is router-less, like ext-net1:
	# the ovn-bgp service plugin owns the subnet's gateway IP as an
	# anycast gateway on the BGP main router. The OVS mode keeps the
	# HA router, gatewayed on the transport network.
	if [ "${MODE}" != "ovn" ] ; then
		echo "-> Creating Octavia LoadBalancer router int-octavia1-router1"
		OCTAVIA_ROUTER_ID=$(openstack router list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='int-octavia1-router1'")
		if [ -z "${OCTAVIA_ROUTER_ID}" ] ; then
			openstack router create --description "Octavia LoadBalancer router for amphora subnet" --ha int-octavia1-router1
		else
			echo "Router int-octavia1-router1 already created"
		fi

		echo "-> Setting-up Octavia LoadBalancer router int-octavia1-router1 external gateway"
		if [ ""$(openstack router show int-octavia1-router1 --format json -c external_gateway_info | jq '.["external_gateway_info"]["network_id"]' -r) = "null" ] ; then
			openstack router set --external-gateway int-provider1 int-octavia1-router1
		else
			echo "External gateway for int-octavia1-router1 already set"
		fi

		echo "-> Adding int-octavia1-subnet1 as interface of int-octavia1-router1"
		SUBNET_PORT_ID=$(openstack router show int-octavia1-router1 --format json -c interfaces_info | jq -r --arg sid "${OCTAVIA_INT_SUBNET}" '.["interfaces_info"][] | select(.subnet_id == $sid) | .port_id')
		if [ -z "${SUBNET_PORT_ID}" ] ; then
			openstack router add subnet int-octavia1-router1 int-octavia1-subnet1
		else
			echo "Subnet int-octavia1-subnet1 already added to int-octavia1-router1"
		fi
	fi

	# With the OVN mode, the ovn-bgp service plugin announces the
	# amphora subnet into the underlay when leak_routes is set on
	# it: the subnet's gateway IP becomes an anycast gateway owned
	# by the BGP main router, and the amphora addresses are
	# advertised as /32 host routes. Without it, the Octavia
	# services on the controllers cannot route to the amphora
	# management addresses. This replaces the "bgp speaker add
	# network" call below, and the router block above.
	if [ "${MODE}" = "ovn" ] ; then
		openstack subnet set --leak-routes int-octavia1-subnet1
	fi

	. /root/oci-openrc

	# With the OVN mode, the ovn-bgp service plugin announces the
	# amphora ports of the flat provider network itself, and there is
	# no dynamic routing speaker API to add networks to.
	if [ "${MODE}" != "ovn" ] ; then
		echo "-> Adding int-provider1 to speaker-leaf2 so it is BGP announced"
		if ! openstack bgp speaker show speaker-leaf2 --format json -c networks | jq '.["networks"][]' -r | grep -q ${OCTAVIA_TRANSPORT_NETWORK} ; then
			openstack bgp speaker add network speaker-leaf2 int-provider1
		else
			echo "int-provider1 already added to speaker-leaf2"
		fi
	fi

}

oci_poc_prov_cloud_create_networks_internal_octavia

exit 0

#LB_MGMT_NET=$(openstack network list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='lb-mgmt-net'")
#if [ -z "${LB_MGMT_NET}" ] ; then
#	openstack network create --external --provider-physical-network external --provider-network-type vlan --provider-segment "${OCTAVIA_NETWORK_SUBNET_LAN}" lb-mgmt-net
#        LB_MGMT_NET=$(openstack network list --name lb-mgmt-net -f value -c ID 2>/dev/null)
#fi
#### Create the subnet
#LB_MGMT_SUBNET=$(openstack subnet list --format csv | q -H -d, "SELECT ID FROM - WHERE Name='lb-mgmt-subnet'")
#if [ -z "${LB_MGMT_SUBNET}" ] ; then
#        openstack subnet create --network lb-mgmt-net \
#                --allocation-pool start=${OCTAVIA_NETWORK_SUBNET_PREFIX}.2,end=${OCTAVIA_NETWORK_SUBNET_PREFIX}.252 --subnet-range ${OCTAVIA_NETWORK_SUBNET_PREFIX}.0/24 --gateway ${OCTAVIA_NETWORK_SUBNET_PREFIX}.1 \
#                --dns-nameserver ${PRIMARY_DNS} --dns-nameserver ${SECONDA_DNS} lb-mgmt-subnet
#        LB_MGMT_SUBNET=$(openstack subnet list --name lb-mgmt-subnet -f value -c ID 2>/dev/null)
#fi
