#!/bin/sh

set -e
#set -x

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

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

usage () {
	echo "Usage: ${ME} --mode ovs|ovn"
	echo "  --mode  Networking mode: ovs or ovn (mandatory)."
	echo "          ovn deploys cl1 with ML2/OVN (no network nodes),"
	echo "          and requires the Hibiscus release of OpenStack."
}

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 [ "${MODE}" = "ovn" ] ; then
	if [ "${debian_release}" = "buster" ] || [ "${debian_release}" = "bullseye" ] || [ "${debian_release}" = "bookworm" ] ; then
		echo "OVN support requires the Hibiscus release of OpenStack, which isn't available on ${debian_release}."
		exit 1
	fi
	echo "===***===> OVN mode: cl1 will be deployed with ML2/OVN, without network nodes"
fi

# The covering routes of the VLAN pool /24s are mode-dependent: the OVS
# mode needs all of them (they are the floating-IP/SNAT return mechanism,
# and the cl1 network nodes' own reachability rides the 113 one), while
# the OVN mode must never announce cl1's pools (the coverings would
# shadow the /32 host routes announced by the compute hosting each
# floating IP), so only cl3's OVS-mode pools stay redistributed. As
# oci-poc-ci owns the mode, it also picks the matching knob value, so
# that switching modes cannot leave a stale value behind.
if [ "${MODE}" = "ovn" ] ; then
	IKVSWITCH_REDISTRIBUTE=${MAP_REDISTRIBUTE_VLAN_SUBNETS_OVN:-117,118,119,120}
else
	IKVSWITCH_REDISTRIBUTE=${MAP_REDISTRIBUTE_VLAN_SUBNETS:-all}
fi

sshi () {
	local HOST
	HOST=$1
	shift

	ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${HOST} "${@}"
}

echo "===***===> Destroying everyting"
oci-poc-vms stop || true
ikvswitch-setup stop || true

echo "===***===> Rebuilding switches"
ikvswitch-setup start --map-redistribute-vlan-subnets ${IKVSWITCH_REDISTRIBUTE}

echo "===***===> Building OCI PoC image"
oci-poc-setup

echo "===***===> Starting oci-poc VMs"
RETRY_NUM=8
CNT=0
while ! oci-poc-vms start && [ "${CNT}" -lt "${RETRY_NUM}" ] ; do
	oci-poc-vms stop || true
	CNT=$(( ${CNT} + 1 ))
done

if [ "${CNT}" -ge "${RETRY_NUM}" ] ; then
	echo "Could not spawn VMs after ${RETRY_NUM} attemps."
	exit 1
fi

echo "===***===> Configuring cluster"
oci-poc-install-cluster-bgp --mode ${MODE}

echo "===> Setting-up quorum queues"
# Needed as RabbitMQ 4.x does not support HA queues
if [ "${debian_release}" != "buster" ] && [ "${debian_release}" != "bullseye" ]  && [ "${debian_release}" != "bookworm" ]; then
        ocicli cluster-set cl1 --rabbitmq-enable-quorum-queues yes
        ocicli cluster-set cl2 --rabbitmq-enable-quorum-queues yes
        ocicli cluster-set cl3 --rabbitmq-enable-quorum-queues yes
fi

echo "===***===> Installing cluster cl2"
ocicli cluster-install cl2

echo "===***===> Fetching cl2 admin password"
CL2_CTRL1=$(ocicli -csv machine-list --filter hostname=cl2-controller-1.infomaniak.ch | q -H -d, "SELECT Cur_ip FROM -")
CL2_ADM_PASS=$(ssh ${CL2_CTRL1} ". /root/oci-openrc ; echo \$OS_PASSWORD")

echo "===***===> Fixing cl1 and cl3 passwords for zabbix and tempest2 users to be same as cl2"
# Get the ID of passwords on the 3 clusters
# Note that zabbix and tempest2 users (both used
# in tempest) are sharing the same pass.
CL1_ZBX_PASS_ID=$(ocicli -csv password-list --filter cluster=1,service=zabbix,passtype=authtoken | q -d, -H "SELECT id from -")
CL2_ZBX_PASS_ID=$(ocicli -csv password-list --filter cluster=2,service=zabbix,passtype=authtoken | q -d, -H "SELECT id from -")
CL3_ZBX_PASS_ID=$(ocicli -csv password-list --filter cluster=3,service=zabbix,passtype=authtoken | q -d, -H "SELECT id from -")

# Get the passwords set on cl2
ZBX_PASS=$(ocicli password-show ${CL2_ZBX_PASS_ID} | grep '^Pass: ' | cut -d' ' -f2)

# Set the same pass on cl1 and cl3
ocicli password-set ${CL1_ZBX_PASS_ID} ${ZBX_PASS}
ocicli password-set ${CL3_ZBX_PASS_ID} ${ZBX_PASS}

echo "===***===> Creating cluster3 keystone endpoints"
ssh ${CL2_CTRL1} ". /root/oci-openrc ; openstack region create cluster3"
ssh ${CL2_CTRL1} ". /root/oci-openrc ; openstack endpoint create --region cluster3 keystone public https://cl2-api.infomaniak.ch/identity"
ssh ${CL2_CTRL1} ". /root/oci-openrc ; openstack endpoint create --region cluster3 keystone admin https://cl2-api.infomaniak.ch/identity"
ssh ${CL2_CTRL1} ". /root/oci-openrc ; openstack endpoint create --region cluster3 keystone internal https://cl2-api.infomaniak.ch/identity"

echo "===***===> Setting cl2 as external keystone for cl1"
ocicli cluster-set cl1 --external-keystone-activate yes --external-keystone-admin-password ${CL2_ADM_PASS} --external-keystone-url https://cl2-api.infomaniak.ch/identity

echo "===***===> Setting cl2 as external keystone for cl3"
ocicli cluster-set cl3 --external-keystone-activate yes --external-keystone-admin-password ${CL2_ADM_PASS} --external-keystone-url https://cl2-api.infomaniak.ch/identity

echo "===> Disabling empty zones for cl1"
ocicli cluster-set cl1 --dns-empty-zones-enable no

echo "===***===> Installing cluster"
ocicli cluster-install cl1

echo "===***===> Installing cluster"
ocicli cluster-install cl3

echo "===***===> Provisioning cluster, OpenStack side"
oci-poc-provision --mode ${MODE}
