#!/bin/sh

set -e
#set -x

if ! [ -r /etc/oci-poc/oci-poc.conf ] ; then
	echo "Cannot read /etc/oci-poc/oci-poc.conf"
fi
. /etc/oci-poc/oci-poc.conf

ME=$(basename $0)

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

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

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 "===***===> 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 "===***===> Installing cluster"
ocicli cluster-install cl1

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

echo "===***===> Provisioning cluster, OpenStack side"
oci-poc-provision
