#!/bin/sh

# Live migration of virtual machine
# arg0 vm localhost host2 [--no-autostart]
# arg0 vm host2 localhost [--no-autostart]
# $1 is VM name
# $2 is from
# $3 is to
# $4 if present must be --no-autostart
# after migration:
#   we disable autostart on from,
#   we enable autostart on to unless 4th arg is --no-autostart

# vi(1) :se tabstop=4

#virsh_migrate_base_cmd_and_args='virsh migrate --live --p2p --tunnelled --persistent --copy-storage-all --verbose --abort-on-error'
virsh_migrate_base_cmd_and_args='virsh migrate --live --persistent --copy-storage-all --verbose --abort-on-error'

# if conditional must be true for good syntax
if \
	case "$#" in
		4)
			case "$4" in
				--no-autostart)
					autostart=--no-autostart
					autostart_disable=--disable
				;;
				*)
					# 4th arg other than --no-autostart - disallowed
					false
				;;
			esac
		;;
		3)
			autostart=--autostart
			autostart_disable=
		;;
		*)
			# bad # of arguments
			false
		;;
	esac &&
	case "$3" in
		localhost)
			case "$2" in
				localhost)
					# to and from can't both be localhost
					false
				;;
				*)
					localhost=to
					non_localhost="$2"
				;;
			esac
		;;
		*)
			case "$2" in
				localhost)
					localhost=from
					non_localhost="$3"
				;;
				*)
					# to and from can't both be non-localhost
					false
				;;
			esac
		;;
	esac &&
	case "$non_localhost" in
		192.168.55.2|192.168.55.25[23])
			:
		;;
		vicki)
			non_localhost=192.168.55.2
		;;
		host2)
			non_localhost=192.168.55.252
		;;
		host1)
			non_localhost=192.168.55.253
		;;
		*)
			# non_localhost isn't a recognized one
			false
		;;
	esac
then
	Name_of_Virtual_Machine="$1"
	case "$localhost" in
		from)
			$virsh_migrate_base_cmd_and_args \
				"$Name_of_Virtual_Machine" \
				qemu+ssh://"$non_localhost"/system &&
			virsh autostart --disable "$Name_of_Virtual_Machine" &&
			ssh -ax -l root "$non_localhost" '
				virsh autostart '"$autostart_disable "'\
					'"$Name_of_Virtual_Machine"'
			'
		;;
		to)
			# try to determine our IP for the subnet we're using
			myip=$(
				ip -4 a s |
				sed -ne '
					s/^    inet \(192\.168\.55\.[0-9]\{1,3\}\)\/.*$/\1/p
					t q
					d
					: q
					q
				'
			) &&
			case "$myip" in
				?*)
					:
				;;
				*)
					echo "$0: failed to determine our IP address, aborting" 1>&2
					exit 1
				;;
			esac
			ssh -ax -l root "$non_localhost" '
				'"$virsh_migrate_base_cmd_and_args"' \
					'\'"$Name_of_Virtual_Machine"\'' \
					qemu+ssh://'"$myip"'/system &&
				virsh autostart --disable \
					'\'"$Name_of_Virtual_Machine"\''
			' &&
			virsh autostart $autostart_disable "$Name_of_Virtual_Machine"
		;;
		*)
			echo "$0: internal error, bad value for localhost(=$localhost), aborting" 1>&2
			exit 1
		;;
	esac
else
	cat <<- __EOT__ 1>&2
		$0: usage:
		$0 Name_of_Virtual_Machine from_host to_host [--no-autostart]
		Exactly one of from_host and to_host must be localhost,
		and that which is not localhost must be a recognized configured host.
	__EOT__
	exit 1
fi
