#!/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

# Check that we really have NUMBER_OF_GUESTS machines available
# before starting anything
check_enough_vms_available () {
	EXPECTED_NUM_OF_SLAVES=${1}

	NUM_VM=$(ocicli -csv machine-list | q -d , -H "SELECT COUNT(*) AS count FROM -")
	if [ ${NUM_VM} -lt ${EXPECTED_NUM_OF_SLAVES} ] ; then
		echo "Num of VM too low... exiting"
		exit 1
	fi
}

check_enough_vms_available $((${NUMBER_OF_GUESTS} - 1))

echo "===> Setting-up IPMI ports on VMs"
for i in $(seq 2 $((${NUMBER_OF_GUESTS} + 1))) ; do
	VM_SERIAL=$(printf "%X\n" $((0xBF + ${i})))
	VNC_PORT=$((9000 + $i))
	echo "Setting IPMI for VM with serial: $VM_SERIAL and VNC port: $VNC_PORT"
	ocicli machine-set-ipmi ${VM_SERIAL} yes 192.168.100.1 ${VNC_PORT} ipmiusr test
done

echo "===> Creating regions and locations"
ocicli swift-region-create swift-region1
ocicli swift-region-create swift-region2
ocicli swift-region-create pub-region

ocicli location-create reg-1-zone-1 swift-region2
ocicli location-create reg-2-zone-1 swift-region1
ocicli location-create reg-2-zone-2 swift-region1
ocicli location-create pub-zone pub-region

echo "===> Creating networks"
ocicli network-create reg1-zone1-net1 192.168.101.0 24 reg-1-zone-1 no
ocicli network-create reg2-zone1-net1 192.168.103.0 24 reg-2-zone-1 no
ocicli network-create reg2-zone2-net1 192.168.104.0 24 reg-2-zone-2 no
#ocicli network-create br-lb 0.0.0.0 24 reg-1-zone-1 no
ocicli network-create pub-net 192.168.106.0 24 pub-zone yes

# Set the IPMI network
if [ "${USE_AUTOMATIC_IPMI_SETUP}" = "yes" ] ; then
	echo "===> Setting-up automatic IPMI assignation"
	ocicli network-create ipmi 192.168.200.0 24 reg-1-zone-1 no
	ocicli network-set ipmi --role ipmi --ipmi-match-addr 192.168.0.0 --ipmi-match-cidr 16
	ssh ${HOST_NETWORK_PREFIX}.2 "sed -i s/automatic_ipmi_numbering=no/automatic_ipmi_numbering=yes/ /etc/openstack-cluster-installer/openstack-cluster-installer.conf" 1>/dev/null 2>/dev/null
	ssh ${HOST_NETWORK_PREFIX}.2 "mkdir -p /var/www/.ssh" 1>/dev/null 2>/dev/null
	ssh ${HOST_NETWORK_PREFIX}.2 "chown www-data:www-data /var/www/.ssh" 1>/dev/null 2>/dev/null
fi

echo "===> Creating cluster cl1"
ocicli cluster-create cl1 infomaniak.ch

echo "===> Adding networks to cl1"
ocicli network-add reg1-zone1-net1 cl1 all 1g2 none
ocicli network-add reg2-zone1-net1 cl1 all 1g2 none
ocicli network-add reg2-zone2-net1 cl1 all 1g4 none
ocicli network-add pub-net cl1 all ens5 none
ocicli network-set pub-net --role vip

#ocicli network-add br-lb cl1 ovs-bridge eth3 none
#ocicli network-set br-lb --bridge-name br-lb

echo "===> Adding controller nodes to cl1"
# 3x Controller machines (includes Swift proxies)
ocicli machine-add C1 cl1 controller reg-1-zone-1
ocicli machine-add C2 cl1 controller reg-2-zone-1
ocicli machine-add C3 cl1 controller reg-2-zone-2

exit 0
