#!/bin/sh

set -e

ocicli_cluster_wait_for () {
	local MACHINE_SERIAL=$1
	local FIELD=$2
	local VALUE=$3
	local CNT=1800
	while [ "${CNT}" -gt 0 ] && [ ""$(ocicli -csv machine-list -a | q -H -d, "SELECT ${FIELD} FROM - WHERE serial='${MACHINE_SERIAL}' OR hostname='${MACHINE_SERIAL}'" 2>/dev/null) != "${VALUE}" ] ; do
		echo -n "."
		sleep 2
		CNT=$((${CNT} - 1))
	done
	if [ "${CNT}" = 0 ] ; then
		echo "timed out."
		exit 1
	else
		echo "ok."
	fi
}

wait_for_ssh () {
	local COUNT CYCLES OTCI_CAN_SSH SSH_HOST
	COUNT=120
	CYCLES=0
	OTCI_CAN_SSH=no
	SSH_HOST=${1}
	echo -n "-> Waiting for ssh: "
	while [ "${OTCI_CAN_SSH}" != "yes" ] && [ ${COUNT} != 0 ] ; do
		if ssh -o "StrictHostKeyChecking no" -o "ConnectTimeout 2" ${SSH_HOST} 'echo -n ""' 1>/dev/null 2>/dev/null ; then
			OTCI_CAN_SSH=yes
		else
			echo -n "."
			COUNT=$(( ${COUNT} - 1 ))
			CYCLES=$(( ${CYCLES} + 1 ))
			sleep 1
		fi
	done
	echo "ok."
	ssh -o "StrictHostKeyChecking no" -o "ConnectTimeout 2" ${SSH_HOST} 'echo -n ""' 1>/dev/null 2>/dev/null
}

otci_remote () {
	if [ "${1}" = "--host" ] ; then
		MYHOST=${2}
		shift
		shift
	else
		MYHOST=192.168.110.2
	fi
	ssh -o "StrictHostKeyChecking no" ${MYHOST} $@ 1>/dev/null 2>/dev/null
}

GENERATED_PASS=$(openssl rand -hex 32)

echo "===> Creating cluster cl2 and location cl2-location-1"
ocicli cluster-create cl2 infomaniak.ch
ocicli swift-region-create cl2-swift-region-1
ocicli location-create cl2-location-1 cl2-swift-region-1

echo "===> Creating network 192.168.110.0/24 for cl2-location-1"
ocicli network-create cl2-network-1 192.168.110.0 24 cl2-location-1 no
ip addr add 192.168.110.1/24 dev ocibr1 || true
ocicli network-add cl2-network-1 cl2 all 1g2 none

echo "===> Adding E6 as external keystone"
ocicli role-create keystone
ocicli machine-add E6 cl2 keystone cl2-location-1
ocicli cluster-set cl1 --external-keystone-activate yes --external-keystone-admin-password ${GENERATED_PASS} --external-keystone-region-prefixed-users yes --external-keystone-url http://192.168.110.2:5000/

echo "===> Setting region of cl1 to blueregion"
ocicli cluster-set cl1 --region-name blueregion

echo "===> Installing E6"
ocicli machine-install-os E6

echo -n "-> Waiting for E6 to be installed:"
ocicli_cluster_wait_for E6 status installed
wait_for_ssh 192.168.110.2

echo "===> Setting-up Keystone in E6"
otci_remote --host 192.168.110.2 "apt-get install default-mysql-server dbconfig-common openstack-deploy -y"

#otci_remote --host 192.168.110.2 ". /usr/share/openstack-deploy/preseed-lib ; osinstall_rcvalue RC_KEYSTONE_AUTHTOKEN \"Keystone authtoken [generated-password]: \" yes ; osinstall_rcvalue RC_KEYSTONE_ADMINPASS \"Keystone admin tenant password [generated-password]: \" no ; osinstall_rcvalue RC_KEYSTONE_SQL_PASS \"Keystone MySQL password [generated-password]: \" yes ; os_install_keystone ${GENERATED_PASS} ${GENERATED_PASS} 192.168.110.2 blueregion ${GENERATED_PASS}"
