#!/bin/sh

# EXPERIMENTAL: never tested

set -e
set -x

usage () {
        echo "$0 <CLUSTER-NAME>"
        echo "This command restores the state of a backuped PoC cluster."
        echo "See oci-poc-save to save the state of a cluster."
        exit 1
}

if [ "${#}" != 1 ] || [ "${1}" = "-h" ] || [ "${1}" = "--help" ] || ["${1}" = "-help" ] ; then
        usage
fi

CLUSTER_NAME=${1}

if ! [ -d /var/lib/openstack-cluster-installer-poc/saved/${CLUSTER_NAME} ] ; then
	echo "${CLUSTER_NAME} doesn't exist"
	exit 1
fi

echo "===> Killing not-installed VMs..."
VMS_PID_FILES=$(ls /var/run/oci-poc/slave-node-*.pid | grep -v ipmisim | tr '\n' ' ')
for i in ${VMS_PID_FILES} ; do
        kill $(cat $i) || true
        rm -f $i
done

echo "===> Killing all IPMI SIM..."
IPMI_SIM_PID_FILES=$(ls /var/run/oci-poc/slave-node-*.ipmisim.pid | tr '\n' ' ')
for i in ${IPMI_SIM_PID_FILES} ; do
	kill $(cat $i) || true
	rm -f $i
done

echo "===> Making backup of .qcow2 files..."
cp -axufv /var/lib/openstack-cluster-installer-poc/saved/${CLUSTER_NAME}/*.qcow2 /var/lib/openstack-cluster-installer-poc/runtime/
cp -axufv /var/lib/openstack-cluster-installer-poc/saved/${CLUSTER_NAME}/*.conf /var/lib/openstack-cluster-installer-poc/ipmi_sim/

echo "===> Starting VMs..."
/usr/bin/ipmi_sim -n -c /var/lib/openstack-cluster-installer-poc/ipmi_sim/pxe-server-node.conf -f /etc/oci-poc/ipmisim1.emu &
echo "-> Waiting 20 seconds for the PXE server to be up..."
sleep 20

for i in $(ls /var/lib/openstack-cluster-installer-poc/ipmi_sim/slave-node-*.conf) ; do
	echo "-> Starting-up $i"
	/usr/bin/ipmi_sim -n -c $i -f /etc/oci-poc/ipmisim1.emu &
	sleep 1
done
