#!/bin/sh

set -e

usage () {
	echo "Wrong parameters. Usage:"
	echo "$0 [--dry-run]"
	exit 1
}

DRY_RUN=no
if [ $# -gt 1 ] ; then
	usage
fi
if [ $# = 1 ] ; then
	if [ "${1}" != "--dry-run" ] ; then
		usage
	fi
	DRY_RUN=yes
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

IPMI_SIM_CONF_DIR=/var/lib/openstack-cluster-installer-poc/ipmi_sim
IPMI_USERNAME=ipmiusr
IPMI_PASSWORD=test
: "${OCI_POC_MAX_STUCK_VMS:=5}"

EXPECTED_SERIALS=""
i=1
while [ "${i}" -le "${NUMBER_OF_GUESTS}" ] ; do
	EXPECTED_SERIALS="${EXPECTED_SERIALS} $(printf "%X" $((0xC0 + ${i})))"
	i=$(( ${i} + 1 ))
done

REGISTERED_SERIALS=$(ocicli -csv machine-list | q -H -d, "SELECT serial FROM -")

MISSING=""
for SERIAL in ${EXPECTED_SERIALS} ; do
	if ! echo "${REGISTERED_SERIALS}" | grep -qx "${SERIAL}" ; then
		MISSING="${MISSING} ${SERIAL}"
	fi
done

if [ -z "${MISSING}" ] ; then
	echo "All ${NUMBER_OF_GUESTS} guest VMs are registered in OCI."
	exit 0
fi

NUM_MISSING=$(echo ${MISSING} | wc -w)
echo "Guest VMs not registered in OCI ( ${NUM_MISSING} ):${MISSING}"

if [ "${NUM_MISSING}" -gt "${OCI_POC_MAX_STUCK_VMS}" ] ; then
	echo "Too many guest VMs missing: not attempting any BMC recovery."
	exit 2
fi

if [ "${DRY_RUN}" = "yes" ] ; then
	echo "Dry run: not attempting any BMC recovery."
	exit 0
fi

for SERIAL in ${MISSING} ; do
	CONF_FILE=$(grep -rl "product=qemu-oci,serial=${SERIAL} " ${IPMI_SIM_CONF_DIR}/*.conf 2>/dev/null | head -n 1)
	if [ -z "${CONF_FILE}" ] ; then
		echo "WARNING: no BMC configuration found for serial ${SERIAL}, skipping."
		continue
	fi
	PORT=$(sed -n "s/^ *addr 0\.0\.0\.0 \([0-9]*\)$/\1/p" "${CONF_FILE}")
	if [ -z "${PORT}" ] ; then
		echo "WARNING: no BMC IPMI port found for serial ${SERIAL} in ${CONF_FILE}, skipping."
		continue
	fi
	if ! ipmitool -I lanplus -H 127.0.0.1 -p ${PORT} -U ${IPMI_USERNAME} -P ${IPMI_PASSWORD} -N 5 -R 2 chassis power cycle ; then
		echo "WARNING: could not power cycle the BMC of serial ${SERIAL} on port ${PORT}, skipping."
	else
		echo "Power cycled the VM of serial ${SERIAL} through its BMC on port ${PORT}."
	fi
done
