#!/bin/bash
##################################################
# upgrade_dom0 1.0
# used to perform a headless dom0 upgrade from
# a an installation image mounted on an HTTP server
##################################################
#################################################################################################
#
# HA-Lizard - Open Source High Availability Framework for Xen Cloud Platform and XenServer
#
# Copyright 2019 Salvatore Costantino
# ha@pulsesupply.com
#
# This file is part of HA-Lizard.
#
#    HA-Lizard is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    HA-Lizard is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with HA-Lizard.  If not, see <http://www.gnu.org/licenses/>.
#
##################################################################################################
THIS_HOSTNAME=$(hostname)
THIS_HOST_UUID=$(xe host-list hostname=$THIS_HOSTNAME --minimal)
if [ "${#THIS_HOST_UUID}" -ne 36 ]
then
	echo "Error finding local host UUID. Exiting.."
	exit 1
fi

echo "${0/\.\//} will perform a headless dom0 upgrade using an install"
echo "image mounted on an external HTTP server. Continue [y|n]"
while :
do
	read CONTINUE
	if [ "$CONTINUE" = "n" ]
	then
		exit 0
	elif [ "$CONTINUE" = "y" ]
	then
		break
	else
		continue
	fi
done

echo "Optionally backup HA-Lizard shared storage settings to the XAPI DB [y|n]"
while :
do
	read CONTINUE
	if [ "$CONTINUE" = "n" ]
	then
		break
	elif [ "$CONTINUE" = "y" ]
	then
		which iscsi-cfg &>/dev/null
		RETVAL=$?
		if [ $RETVAL -ne 0 ]
		then
			echo "iscsi-cfg missing. Cannot backup settings"
			exit 0
		else
			iscsi-cfg backup 
			break
		fi
	else
		continue
	fi
done

echo "Enter the URL for the installation image (HTTP://domain/path/to/files)"
read URL
TEST_URL_RESULT=$(xe host-call-plugin plugin=prepare_host_upgrade.py host-uuid=$THIS_HOST_UUID fn=testUrl args:url=$URL/)
if [ "$TEST_URL_RESULT" != "true" ]
then
	echo "URL validation failed. Exiting..."
	exit 1
else
	echo "URL Validation succeeded. Preparing host for upgrade"
	PREPARE_HOST_RESULT=$(xe host-call-plugin plugin=prepare_host_upgrade.py host-uuid=$THIS_HOST_UUID fn=main args:url=$URL/)
	if [ "$PREPARE_HOST_RESULT" != "true" ]
	then
		echo "Error preparing host for update. Exiting..."
		exit 1
	else
		echo "Host is ready for upgrade. Reboot now [y|n]"
		while :
		do
			read REBOOT
			if [ "$REBOOT" = "n" ]
			then
				exit 0
			elif [ "$REBOOT" = "y" ]
			then
				reboot
			else
				continue
			fi
		done
	fi
fi

