#!/usr/bin/env bash
#
# esmigrate - Erigones VM/zones/dataset migrator
#

set -u
set -o pipefail


###############################################################
# globals
###############################################################

ERIGONES_HOME=${ERIGONES_HOME:-"/opt/erigones"}
SELF="${ERIGONES_HOME}/bin/esmigrate"
PROG="$(basename "$0")"
# shellcheck disable=SC1090
. "${ERIGONES_HOME}"/bin/eslib/functions.sh


declare MODE			# string: "migrate" or "agent/agent-verbose"
declare VERBOSE=""		# string: print info messages if non-empty
declare VM_STATUS_SRC	# string: "running" or "stopped"
declare VM_BRAND_SRC	# string: "kvm" or "..."
declare VM_QEMU_OPTS_SRC	# string: vmadm's qemu_extra_opts
declare VM_TMP_MEM_FILE	# string: path to store contents of VM's memory on target host (live migration)
declare VM_STOP="true"	# bool: whether to stop the VM before final send/recv
declare VM_START=""		# bool: whether to start the VM after successful finish
declare VM_READY=""		# bool: whether destination VM was started during live migration
declare VM_RESUME=""	# bool: whether to resume the VM after successful finish
declare VM_CORES_RM=""	# bool: VM's cores dataset was removed if non-empty
declare VM_DETACHED=""	# bool: source zone was detached if non-empty
declare VM_DETACHED_FAKE=""	# bool: if not-empty, source zone was not detached, however SUNWdetached.xml was created (live migration)
declare VM_ATTACHED=""	# bool: destination zone was attached if non-empty
declare VM_MEM_DUMP=""	# bool: VM memory dump was create if non-empty
declare PRINT_JSON=""	# bool: print VM json to stdout after successful migration
declare VM_VNC_PORT=""	# int: change the VNC port property on VM migrated to another host (KVM)
declare UUID_SRC		# string: "<uuid>"
declare JSON_SRC		# string: "{...}"
declare DEST_HOST		# string: IP address
declare DEST_POOL		# string: pool name
declare -a DEST_DISK	# array: target pools or target IDs
declare DS_ROOT			# string: "<src-pool>/<uuid> <dest-pool>/<uuid>"
declare -a DS_DATA		# array: ["<src-pool>/<uuid>-disk1 <dest-pool>/<uuid>-disk1", "<src-pool>/<uuid>-disk2 <dest-pool>/<uuid>-disk2"]
declare SIZE=0			# long: total transfer size in bytes
declare -a DS_RECV=()	# array: migrated datasets
declare -a SNAPSHOTS=()	# array: names of existing snapshots
declare -ri CORE_QUOTA=102400									# int: maximum size in MB of VM's cores dataset
declare -ri VM_MAX_DISKS=8										# int: maximum number of supported disks
# shellcheck disable=SC2155
declare -i TIME_STARTED=$(get_timestamp)						# int: timestamp
declare -i DOWNTIME_STARTED										# int: timestamp set shortly before vmadm stop
declare -i DOWNTIME=0											# int: downtime in seconds
declare CFG_BACKUP_EXT=".bkp-${TIME_STARTED}"					# string: backup config file extension
declare -a DS_CHANGE=("${SED}" -i "${CFG_BACKUP_EXT}")			# array: sed commands for updating zonecfg.xml
declare -a DS_ROOT_CHANGE=("${SED}" -i "${CFG_BACKUP_EXT}")		# array: sed command for updating index
declare -a CFG_CHANGED=()										# array: changed config files
declare -a DEST_IMAGES=()										# array: list of "dest-dataset image_uuid" used by source VM
declare -r TMP_DIR="/var/tmp"									# string: existing directory for temporary files
declare -r VM_QMP_SOCK="/tmp/vm.qmp"							# string: path to QMP socket (inside zone root) -> VMS_VM_QEMU_GUEST_AGENT_SOCKET
declare -r VM_MIGRATION_SOCK="/tmp/vm.migration"				# string: path to migration file socket (inside zone root)
declare -r VM_QEMU_OPTS_DST_APPEND="-incoming unix:${VM_MIGRATION_SOCK}"
declare -r VM_MEM_FILE_SUFFIX="ramdump"							# string: suffix for memory dumps in TMP_DIR
declare -r PROG_PID=$$											# int: PID of main
declare VM_MEM_TRANSFER_PID=""									# int: PID of _transfer_kvm_ram (socat) background process
declare VM_DISK_TRANSFER_PID=""									# int: PID of _transfer_kvm_disk (send/recv) background process

###############################################################
# exit codes
###############################################################

declare -ri OK=0
declare -ri ERR_INPUT=1
declare -ri ERR_DH_CHECK=2
declare -ri ERR_VM_CHECK=3
declare -ri ERR_VM_IMG_CHECK=4
declare -ri ERR_DS_CHECK=5
declare -ri ERR_DS_SNAP=6
declare -ri ERR_DS_SENDRECV=7
declare -ri ERR_VM_STOP=8
declare -ri ERR_VM_START=8
declare -ri ERR_VM_DETACH=9
declare -ri ERR_VM_ATTACH=10
declare -ri ERR_DS_CORE=11
declare -ri ERR_VM_XML=12
declare -ri ERR_VM_AFTER_CHECK=13
declare -ri ERR_VM_MEM_SENDRECV=14
declare -ri ERR_ASSERT=99


###############################################################
# helpers
###############################################################

function techo() {
	local msg=$*

	[[ -z "${VERBOSE}" ]] && return 0

	echo "[$(${DATE} '+%Y-%d-%m %H:%M:%S')] ${msg}"
}

function usage() {
	${CAT} << EOF
Usage: ${PROG} {migrate} [parameters]

  Migrate mode parameters:
    <uuid>                  source guest uuid
    -H <dest-host>          IP address of the target host
    -p <dest-pool>          is the destination pool for the root zone [KVM] or all datasets [OS]
    -[n] <dest-disk-pool>   specifies another destination pool for disk id [n], 
                            where [n] is the disk id in the disks array starting with 0 [KVM]
    -C <vnc-port>           change VNC port for VM migrated to remote host [KVM]
    -L                      perform live migration [KVM, EXPERIMENTAL]
    -v                      print information about each step of the migration process
    -j                      print final guest json to stderr after successful migration

  Migrate mode examples (guest must be stopped or running):

    - Migrate one guest disk into another pool (local) [KVM]:
      # ${PROG} migrate <uuid> -[n] <dest-disk-pool>

    - Migrate guest root zone into another pool (including delegated datasets of an OS zone) (local) [KVM, OS]:
      # ${PROG} migrate <uuid> -p <dest-pool>

    - Migrate whole OS zone on to another host (remote) [OS]:
      # ${PROG} migrate <uuid> -H <dest-host> [-p <dest-pool>]

    - Migrate whole guest on to another host (remote) [KVM]:
      # ${PROG} migrate <uuid> -H <dest-host> [-L] [-C <vnc-port>] [-p <dest-pool>] [-[n] <dest-disk-pool>]

EOF
}

start_downtime() {
	DOWNTIME_STARTED=$(get_timestamp)
}

stop_downtime() {
	local -i downtime_ended

	downtime_ended=$(get_timestamp)
	DOWNTIME=$((downtime_ended - DOWNTIME_STARTED))
}

check_pid() {
	local checkpid="${1}"

	kill -0 "${checkpid}" &> /dev/null
}

is_kvm() {
	[[ "${VM_BRAND_SRC}" == "kvm" ]]
}


###############################################################
# stage 1: parse input, VM json and check requirements
###############################################################

verbose_stage1() {
	[[ -z "${VERBOSE}" ]] && return

	local a_ds_root
	local a_ds_data
	local remote

	if [[ -z "${DEST_HOST}" ]]; then
		remote="locally"
	else
		remote="to ${DEST_HOST}"
	fi

	echo "Going to transfer following datasets ${remote}:"

	if [[ -n "${DS_ROOT}" ]]; then
		# shellcheck disable=SC2206
		a_ds_root=(${DS_ROOT})
		echo " * ${a_ds_root[0]} -> ${a_ds_root[1]}"
	fi

	if [[ "${#DS_DATA[@]}" -ne 0 ]]; then
		for a_ds_data in "${DS_DATA[@]}"; do
			# shellcheck disable=SC2206
			a_ds_data=(${a_ds_data})
			echo " * ${a_ds_data[0]} -> ${a_ds_data[1]}"
		done
	fi

	echo
}

validate_dest_host_ssh() {
	if [[ -n "${DEST_HOST}" ]]; then
		test_ssh "${DEST_HOST}" || die ${ERR_DH_CHECK} "Target host is unreachable!"
	fi
}

_dest_host_cmd() {
	local -a cmd=("${@}")
	local agent

	if [[ -n "${VERBOSE}" ]]; then
		agent="agent-verbose"
	else
		agent="agent"
	fi

	if [[ -n "${DEST_HOST}" ]]; then
		run_ssh "root@${DEST_HOST}" -- "${SELF}" "${agent}" "$(printf '%q ' "${cmd[@]}")"
	else
		"${cmd[@]}"
	fi
}

_set_vm_status_src() {
	VM_STATUS_SRC=$(_vm_status "${UUID_SRC}")
}

set_vm_status_src() {
	_set_vm_status_src

	[[ -z "${VM_STATUS_SRC}" ]] && die ${ERR_VM_CHECK} "Source VM does not exist!"

	[[ "${VM_STATUS_SRC}" != "running" && "${VM_STATUS_SRC}" != "stopped" ]] && \
		die ${ERR_VM_CHECK} "Source VM is not in running or stopped state!"
}

set_vm_json_src() {
	JSON_SRC=$(_vm_json "${UUID_SRC}")
}

set_vm_brand_src() {
	VM_BRAND_SRC=$(_vm_brand "${JSON_SRC}")
}

set_vm_properties_src() {
	if is_kvm; then
		if [[ -z "${VM_STOP}" ]]; then  # live migration
			VM_TMP_MEM_FILE="${TMP_DIR}/${UUID_SRC}.${VM_MEM_FILE_SUFFIX}.${PROG_PID}"
			VM_QEMU_OPTS_SRC=$(_vm_property "${JSON_SRC}" "qemu_extra_opts")
			# qemu_extra_opts must be defined (else update_zone_xml would fail)
			[[ -z "${VM_QEMU_OPTS_SRC}" ]] && \
				die ${ERR_VM_CHECK} "Source VM configuration is missing the \"qemu_extra_opts\" property"
		fi
	fi
}

validate_dataset() {
	local ds="$1"

	_zfs_dataset_exists "${ds}" &> /dev/null || die ${ERR_DS_CHECK} "Invalid dataset: ${ds}"
}

get_dataset_property() {
	local ds="$1"
	local prop="$2"

	_zfs_dataset_property "${ds}" "${prop}" 2> /dev/null || die ${ERR_DS_CHECK} "Invalid dataset property: ${prop}"
}

_switch_ds_pool() {
	local ds="$1"
	local pool="$2"
	# shellcheck disable=SC2206
	local a_ds=(${ds//// })

	a_ds[0]="${pool}"
	join "/" "${a_ds[@]}"
}

_add_ds_change() {
	local src="$1"
	local dst="$2"
	local root="${3:-""}"

	DS_CHANGE+=("-e")
	DS_CHANGE+=("s#${src}\"#${dst}\"#")

	if [[ -n "${root}" ]]; then
		DS_ROOT_CHANGE+=("-e")
		DS_ROOT_CHANGE+=("s#${src}#${dst}#")
	fi
}

_set_ds_root_migrate() {
	# shellcheck disable=SC2155
	local src=$(_vm_zfs_filesystem "${JSON_SRC}")
	local dst
	local img

	[[ -z "${src}" ]] && die ${ERR_DS_CHECK} "Missing root dataset property in source VM definition!"

	validate_dataset "${src}"

	if [[ -n "${DEST_POOL}" ]]; then
		dst=$(_switch_ds_pool "${src}" "${DEST_POOL}")
		_add_ds_change "${src}" "${dst}" "root"
	else
		dst="${src}"
	fi

	DS_ROOT="${src} ${dst}"

	img=$(_vm_property "${JSON_SRC}" "image_uuid")
	[[ -n "${img}" ]] && DEST_IMAGES+=("${dst} ${img}")
}

_set_ds_data_zone_migrate() {
	# shellcheck disable=SC2155
	local src=$(_vm_property "${JSON_SRC}" "datasets.0")
	local dst

	[[ -z "${src}" ]] && return

	validate_dataset "${src}"

	if [[ -n "${DEST_POOL}" ]]; then
		dst=$(_switch_ds_pool "${src}" "${DEST_POOL}")
		_add_ds_change "${src}" "${dst}"
	else
		dst="${src}"
	fi

	DS_DATA[0]="${src} ${dst}"
}

_set_ds_data_kvm_migrate() {
	local src
	local dst
	local ids
	local id
	local img

	if [[ -n "${DEST_HOST}" ]]; then  # remote migration: set all source VM disks
		ids=$(seq 0 $((VM_MAX_DISKS-1)))
	else  # local migration: set only selected source VM disks
		ids="${!DEST_DISK[*]}"
	fi

	for id in ${ids}; do
		src=$(_vm_property "${JSON_SRC}" "disks.${id}.zfs_filesystem")

		if [[ -z "${src}" ]]; then
			[[ -n "${DEST_DISK[$id]:-}" ]] && die ${ERR_DS_CHECK} "Undefined disk ID: ${id}"

			continue
		fi

		validate_dataset "${src}"

		if [[ -n "${DEST_DISK[$id]:-}" ]]; then
			dst=$(_switch_ds_pool "${src}" "${DEST_DISK[$id]}")
			_add_ds_change "${src}" "${dst}"
		else
			dst="${src}"
		fi

		DS_DATA[$id]="${src} ${dst}"

		img=$(_vm_property "${JSON_SRC}" "disks.${id}.image_uuid")
		[[ -n "${img}" ]] && DEST_IMAGES+=("${dst} ${img}")
	done
}

set_datasets_migrate() {
	# Prepare ${DS_ROOT} and ${DS_DATA}
	DS_ROOT=""
	DS_DATA=()

	if [[ -n "${DEST_HOST}" || -n "${DEST_POOL}" ]]; then  # remote or root pool change
		_set_ds_root_migrate

		if ! is_kvm; then  # add OS zone delegate dataset only when root pool is migrated
			_set_ds_data_zone_migrate
		fi
	fi

	if is_kvm; then
		_set_ds_data_kvm_migrate  # more remote and local migration checks inside function
	fi
}

_check_image() {
	local image_uuid="$1"
	local pool="$2"

	_dest_host_cmd _image_exists "${image_uuid}" "${pool}" || \
		die ${ERR_VM_IMG_CHECK} "VM image ${image_uuid} not installed on target pool ${pool}"
}

_validate_images() {
	local dst_img
	local a_dst_img

	if [[ "${#DEST_IMAGES[@]}" -ne 0 ]]; then
		for dst_img in "${DEST_IMAGES[@]}"; do
			# shellcheck disable=SC2206
			a_dst_img=(${dst_img})
			_check_image "${a_dst_img[1]}" "${a_dst_img[0]%%/*}"
		done
	fi
}

_validate_kvm_live_migration() {
	# We need to make sure that there is enough free space in /var/tmp on destination host;
	# The memory dump can be larger than the actual RAM size of the VM and we don't want to 
	# max out the disk space in /var/tmp.
	local vm_ram_reserve=2097152
	local vm_ram_size
	local tmp_dir_free

	vm_ram_size=$(_vm_property "${JSON_SRC}" "ram")  # MB
	tmp_dir_free=$(_dest_host_cmd _zfs_dataset_property "${TMP_DIR}" "available")  # bytes

	[[ -z "${vm_ram_size}" || -z "${tmp_dir_free}" ]] && \
		die ${ERR_VM_CHECK} "Unexpected error when checking temporary free space on target host"

	[[ "$((vm_ram_size*1024*1024+vm_ram_reserve))" -ge "${tmp_dir_free}" ]] && \
		die ${ERR_VM_CHECK} "Not enough free space in temp folder \"${TMP_DIR}\" on target host"
}

validate_dest_host_migrate() {
	# TODO: Check pools, nic_tags, images, free space and if the same uuid is not defined, datasets should not exist
	_validate_images

	if is_kvm; then
		# KVM-only validators
		if [[ -z "${VM_STOP}" ]]; then
			_validate_kvm_live_migration
		fi
	fi
}

validate_kvm_qmp() {
	# Makes sense only for live migration of KVM to remote host
	[[ -z "${DEST_HOST}" || -n "${VM_STOP}" ]] && return 0

	local qmp_socket="/${DS_ROOT%% *}/root${VM_QMP_SOCK}"

	[[ -S "${qmp_socket}" ]] || die ${ERR_VM_CHECK} "Source VM QMP socket doest not exist"

	_vm_qmp_cmd "${qmp_socket}" "is-running" &> /dev/null || die ${ERR_VM_CHECK} "Source VM QMP status check failed"
}


###############################################################
# stage 2: zone detach/attach, snapshots and send/recv
###############################################################

_create_core_dataset() {
	local dataset="$1"
	local mountpoint="$2"

	${ZFS} create -p -o mountpoint="${mountpoint}" "${dataset}"
}

_get_core_dataset() {
	local root_ds="$1"
	# shellcheck disable=SC2206
	local a_ds=(${root_ds//// })

	echo "${a_ds[0]}/cores/${a_ds[1]}"
}

destroy_core_dataset() {
	# Makes sense only for remote migration and stopped VM
	[[ -z "${DEST_HOST}" || "${VM_STATUS_SRC}" == "running" ]] && return 0
	[[ -z "${DS_ROOT}" ]] && die ${ERR_DS_CORE} "Root dataset is not set: ${UUID_SRC}"

	# shellcheck disable=SC2155
	local core_ds="$(_get_core_dataset "${DS_ROOT%% *}")"

	if _zfs_dataset_exists "${core_ds}" &> /dev/null; then
		${ZFS} destroy "${core_ds}" || die ${ERR_DS_CORE} "Failed to destroy source VM's cores dataset: ${core_ds}"
		techo "Destroyed source VM's cores dataset: ${core_ds}"
		VM_CORES_RM="true"
	fi
}

create_core_dataset_err() {
	# Emergency re-creation of VM's cores dataset on source host (opposite of destroy_core_dataset)
	# Makes sense only for remote migration
	[[ -z "${DEST_HOST}" ]] && return 0
	[[ -z "${VM_CORES_RM}" ]] && return 0  # Skip emergency zfs create when allright was run

	# shellcheck disable=SC2155
	local core_ds="$(_get_core_dataset "${DS_ROOT%% *}")"

	if _zfs_dataset_exists "${core_ds}"; then
		VM_CORES_RM=""
		techo "Source VM's cores dataset exists: ${core_ds}"
	else
		if _create_core_dataset "${core_ds}" "/${DS_ROOT%% *}/cores"; then
			VM_CORES_RM=""
			techo "Re-created VM's cores dataset: ${core_ds}"
		else
			echo "Failed to create source VM's cores dataset: ${core_ds}" 1>&2
		fi
	fi
}

_fake_zone_detach() {
	# Called from zone_detach

	[[ -n "${VM_DETACHED_FAKE}" ]] && return 0

	cp "/etc/zones/${UUID_SRC}.xml" "/${DS_ROOT%% *}/SUNWdetached.xml" || \
		die ${ERR_VM_DETACH} "Failed to fake-detach source VM: ${UUID_SRC}"
	VM_DETACHED_FAKE="true"
	techo "Fake-detached source VM: ${UUID_SRC}"
}

_fake_zone_attach_err() {
	# Emergency zone attach on source host (opposite of _fake_zone_detach)
	# Called from zone_attach_err

	[[ -z "${VM_DETACHED_FAKE}" ]] && return 0

	if rm -f "/${DS_ROOT%% *}/SUNWdetached.xml"; then
		VM_DETACHED_FAKE=""
	fi
}

zone_detach() {
	# Makes sense only for remote migration
	[[ -z "${DEST_HOST}" ]] && return 0

	# Live migration -> fake detach
	if [[ -z "${VM_STOP}" ]]; then
		_fake_zone_detach
		return 0
	fi

	# Otherwise it makes sense only for stopped VM
	[[ "${VM_STATUS_SRC}" == "running" ]] && return 0

	_zone_detach "${UUID_SRC}" || die ${ERR_VM_DETACH} "Failed to detach source VM: ${UUID_SRC}"
	VM_DETACHED="true"
	techo "Detached source VM: ${UUID_SRC}"
}

zone_attach_err() {
	# Emergency zone attach on source host (opposite of zone_detach)
	# Makes sense only for remote migration
	[[ -z "${DEST_HOST}" ]] && return 0

	# Live migration -> fake detach was run
	if [[ -z "${VM_STOP}" ]]; then
		_fake_zone_attach_err
		return 0
	fi

	[[ -z "${VM_DETACHED}" ]] && return 0  # Skip emergency attaching when allright was run

	if _zone_attach "${UUID_SRC}"; then
		VM_DETACHED=""
		techo "Attached source VM: ${UUID_SRC}"
	else
		echo "Failed to attach source VM: ${UUID_SRC}" 1>&2
	fi
}

_create_snapshot() {
	local snap="$1"
	local target="${2:-"source"}"
	local recursive="${3:-"false"}"
	local msg=

	[[ "${recursive}" == "true" ]] && msg=" recursively"

	_zfs_snap "${snap}" "null" "" "${recursive}" || die ${ERR_DS_SNAP} "Could not create ${target} snapshot:${msg} ${snap}"

	techo "Created ${target} snapshot${msg}: ${snap}"
}

_destroy_snapshot() {
	local snap="$1"
	local target="${2:-"source"}"
	local recursive="${3:-"false"}"
	local options=
	local msg=

	if [[ "${recursive}" == "true" ]]; then
		options="-r"
		msg=" recursively"
	fi

	if "${ZFS}" destroy -f ${options} "${snap}"; then
		techo "Destroyed ${target} snapshot${msg}: ${snap}"
	else
		echo "Could not destroy ${target} snapshot${msg}: ${snap}" 1>&2
	fi
}

_get_snapshot_size() {
	local snapshot="$1"
	local snapshot_previous="${2:-}"
	local target="${3:-"source"}"
	local size

	size=$(_zfs_send_size "${snapshot}" "${snapshot_previous}")

	# shellcheck disable=SC2181
	[[ ${?} -ne 0 || -z "${size}" ]] && die ${ERR_DS_SNAP} "Could not determine ${target} snapshot size"

	echo "${size}"
}

_create_snapshots() {
	local snapshot="$1"
	local snapshot_previous="${2:-}"
	local zvols_only="${3:-}"
	local ds_data
	local dsnap
	local size

	if [[ -n "${DS_ROOT}" && -z "${zvols_only}" ]]; then
		dsnap="${DS_ROOT%% *}@${snapshot}"
		_create_snapshot "${dsnap}"

		size=$(_get_snapshot_size "${dsnap}" "${snapshot_previous}")
		((SIZE+=size))
	fi

	if [[ "${#DS_DATA[@]}" -ne 0 ]]; then
		for ds_data in "${DS_DATA[@]}"; do
			dsnap="${ds_data%% *}@${snapshot}"
			# create source snap recursively (possible delegated datasets)
			_create_snapshot "${dsnap}" "source" "true"

			size=$(_get_snapshot_size "${dsnap}" "${snapshot_previous}")
			((SIZE+=size))
		done
	fi
}

create_snapshots() {
	local zvols_only="${1:-}"
	local -i count="${#SNAPSHOTS[@]}"
	local -i id="$((count+1))"
	# shellcheck disable=SC2155
	local snapname="esmigrate-${id}-$(get_timestamp_ns)"
	local snapname_previous=""

	SNAPSHOTS+=("${snapname}")

	if [[ "${count}" -ge 1 ]]; then
		snapname_previous="${SNAPSHOTS[${count}-1]}"
	fi

	if [[ -n "${zvols_only}" ]]; then
		[[ -z "${snapname_previous}" ]] && die ${ERR_ASSERT} "Unexpected situation in create_snapshots()"
	fi

	_create_snapshots "${snapname}" "${snapname_previous}" "${zvols_only}"
}

_destroy_snapshots() {
	local snapshot="$1"
	local ds_data

	if [[ -z "${snapshot}" && "${snapshot}" == "%" ]]; then
		die ${ERR_ASSERT} "Missing or invalid snapshot name in _destroy_snapshots()"
	fi

	if [[ -n "${DS_ROOT}" ]]; then
		_destroy_snapshot "${DS_ROOT%% *}@${snapshot}"
	fi

	if [[ "${#DS_DATA[@]}" -ne 0 ]]; then
		for ds_data in "${DS_DATA[@]}"; do
			# destroy source snap recursively (possible delegated datasets)
			_destroy_snapshot "${ds_data%% *}@${snapshot}" "source" "true"
		done
	fi
}

destroy_snapshots() {
	if [[ "${#SNAPSHOTS[@]}" -ne 0 ]]; then
		# Destroy all snapshots created after first esmigrate snapshot!
		_destroy_snapshots "${SNAPSHOTS[0]}%"
		SNAPSHOTS=()
	fi
}

_recv_dataset_remote() {
	local dst="$1"
	local force="${2:-""}"

	if [[ "${force}" == "true" ]]; then
		# shellcheck disable=SC2086
		run_mbuffer | ${ZFS} recv -F ${dst}
	else
		# shellcheck disable=SC2086
		run_mbuffer | ${ZFS} recv ${dst}
	fi
}

_send_recv_dataset() {
	local dst="$1"
	local src="$2"
	local src2="${3:-}"
	local force=""
	local params
	local remote
	local msg

	if [[ -z "${DEST_HOST}" ]]; then
		remote="locally"

		# Safety catch for rewritting same dataset locally
		[[ "${dst}" == "${src%%@*}" ]] && die ${ERR_DS_SENDRECV} "Cannot send/receive the same source/destination dataset: ${dst}"
	else
		remote="to ${DEST_HOST}"
	fi

	if [[ -z "${src2}" ]]; then
		msg="Sending dataset: ${src} -> ${dst} (${remote}) ..."
		params="-R -p ${src}"
	else
		msg="Sending incremental dataset: ${src2} -> ${dst} (${remote}) ..."
		params="-R -i ${src} ${src2}"
		force="true"
	fi

	techo "${msg}"

	if [[ -z "${DEST_HOST}" ]]; then
		[[ -n "${force}" ]] && force="-F"
		# shellcheck disable=SC2086
		${ZFS} send ${params} | ${ZFS} recv ${force} ${dst}
	else
		# shellcheck disable=SC2086
		${ZFS} send ${params} | run_mbuffer | run_ssh "root@${DEST_HOST}" -- "${SELF} agent _recv_dataset_remote ${dst} ${force}"
	fi

	# shellcheck disable=SC2181
	if [[ $? -eq 0 ]]; then
		[[ -z "${src2}" ]] && DS_RECV+=("${dst}")  # Save copied dataset name (useful for emergency cleanup)

		techo "Successfully sent/received dataset: ${dst} (${remote})"
	else
		die ${ERR_DS_SENDRECV} "Send/receive failed"
	fi
}

_send_recv_datasets_init() {
	local snap0="${1}"
	local a_ds_root
	local a_ds_data

	if [[ -n "${DS_ROOT}" ]]; then
		# shellcheck disable=SC2206
		a_ds_root=(${DS_ROOT})
		_send_recv_dataset "${a_ds_root[1]}" "${a_ds_root[0]}@${snap0}"
	fi

	if [[ "${#DS_DATA[@]}" -ne 0 ]]; then
		for a_ds_data in "${DS_DATA[@]}"; do
			# shellcheck disable=SC2206
			a_ds_data=(${a_ds_data})

			# The OS zone delegated dataset is a child and send together with the DS_ROOT
			if [[ "${MODE}" == "migrate" ]] && ! is_kvm; then
				DS_RECV+=("${a_ds_data[1]}")  # but we still want to mark it as received
			else
				_send_recv_dataset "${a_ds_data[1]}" "${a_ds_data[0]}@${snap0}"
			fi
		done
	fi
}

send_recv_datasets_init() {
	create_snapshots  # Appends new snapshot name to SNAPSHOTS array
	_send_recv_datasets_init "${SNAPSHOTS[0]}"
}

_send_recv_datasets_incr() {
	local snap1="${1}"
	local snap2="${2}"
	local zvols_only="${3:-}"
	local a_ds_root
	local a_ds_data

	if [[ -n "${DS_ROOT}" && -z "${zvols_only}" ]]; then
		# shellcheck disable=SC2206
		a_ds_root=(${DS_ROOT})
		_send_recv_dataset "${a_ds_root[1]}" "${a_ds_root[0]}@${snap1}" "${a_ds_root[0]}@${snap2}"
	fi

	if [[ "${#DS_DATA[@]}" -ne 0 ]]; then
		# The OS zone delegated dataset is a child and send together with the DS_ROOT
		[[ "${MODE}" == "migrate" ]] && ! is_kvm && return 0

		for a_ds_data in "${DS_DATA[@]}"; do
			# shellcheck disable=SC2206
			a_ds_data=(${a_ds_data})
			_send_recv_dataset "${a_ds_data[1]}" "${a_ds_data[0]}@${snap1}" "${a_ds_data[0]}@${snap2}"
		done
	fi
}

send_recv_datasets_incr() {
	local zvols_only="${1:-}"
	local -i count

	create_snapshots "${zvols_only}"  # Appends new snapshot name to SNAPSHOTS array
	count=${#SNAPSHOTS[@]}
	_send_recv_datasets_incr "${SNAPSHOTS[${count}-2]}" "${SNAPSHOTS[${count}-1]}" "${zvols_only}"
}

send_recv_zvols_incr() {
	send_recv_datasets_incr "zvols_only"
}

stop_vm() {
	local msg

	[[ "${VM_STATUS_SRC}" == "stopped" ]] && return 1

	if [[ -z "${VM_STOP}" ]]; then
		techo "VM is not stopped, but skipping VM shutdown as requested!"
		return 1
	fi

	techo "Stopping VM ${UUID_SRC} ..."
	start_downtime
	msg=$(_vm_stop "${UUID_SRC}")

	# shellcheck disable=SC2181
	[[ $? -ne 0 ]] && die ${ERR_VM_STOP} "VM ${UUID_SRC} shutdown failed"

	sleep 10  # Give vmadm some breathe time to change the status to stopped state
	_set_vm_status_src

	[[ "${VM_STATUS_SRC}" != "stopped" ]] && die ${ERR_VM_STOP} "VM ${UUID_SRC} did not reach stopped state"

	VM_START="true"
	techo "$(trim "${msg}")"

	return 0
}


###############################################################
# stage 3: prepare target root zone/VM
###############################################################

update_zone_xml() {
	local zonecfg
	local index="/etc/zones/index"
	local -a update_cmd=("${DS_CHANGE[@]}")
	local qemu_extra_opts

	if [[ -n "${DEST_HOST}" ]]; then  # remote migration -> zone was detached and we update SUNWdetached.xml on target host
		zonecfg="/${DS_ROOT#* }/SUNWdetached.xml"

		# Disable auto boot
		if is_kvm; then
			update_cmd+=("-e")
			# shellcheck disable=SC1117
			update_cmd+=("s#\(<attr .*name=\"vm-autoboot\" .*value=\)\"true\"#\1\"false\"#")

			if [[ -n "${VM_VNC_PORT}" ]]; then
				# Change VNC port
				update_cmd+=("-e")
				# shellcheck disable=SC1117
				update_cmd+=("s#\(attr name=\"vnc-port\" .*value=\)\"[^\"]*\"#\1\"${VM_VNC_PORT}\"#")
			fi

			if [[ -z "${VM_STOP}" ]]; then
				# Add live migration socket to qemu_extra_opts
				qemu_extra_opts="$(base64_encode "${VM_QEMU_OPTS_SRC} ${VM_QEMU_OPTS_DST_APPEND}" | tr -d '\n')"
				update_cmd+=("-e")
				# shellcheck disable=SC1117
				update_cmd+=("s#\(attr name=\"qemu-extra-opts\" .*value=\)\"[^\"]*\"#\1\"${qemu_extra_opts}\"#")
			fi
		else
			update_cmd+=("-e")
			# shellcheck disable=SC1117
			update_cmd+=("s#\(<zone .*autoboot=\)\"true\"#\1\"false\"#")
		fi
	else  # local migration (no zone detach/attach) -> update /etc/zones/<uuid>.xml
		zonecfg="/etc/zones/${UUID_SRC}.xml"
	fi

	# First three commands are sed defaults
	if [[ "${#update_cmd[@]}" -gt 3 ]]; then
		update_cmd+=("${zonecfg}")

		_dest_host_cmd "${update_cmd[@]}" || die ${ERR_VM_XML} "Could not update zone configuration: ${zonecfg}"
		techo "Updated zone configuration: ${zonecfg}"
		# Save changed zone configuration xml (makes sense only for local migration)
		[[ -z "${DEST_HOST}" ]] && CFG_CHANGED+=("${zonecfg}")
	fi

	if [[ -z "${DEST_HOST}" && "${#DS_ROOT_CHANGE[@]}" -gt 3 ]]; then
		# local migration (no zone detach/attach) + zone root change -> update zone root in /etc/zones/<uuid>.xml
		DS_ROOT_CHANGE+=("${index}")

		"${DS_ROOT_CHANGE[@]}" || die ${ERR_VM_XML} "Could not update zone index: ${index}"
		techo "Updated zone index: ${index}"
		CFG_CHANGED+=("${index}")
	fi
}

update_zone_xml_err() {
	# Emergency rollback of changed zone xml files (opposite of update_zone_xml)
	[[ "${MODE}" != "migrate" ]] && return 0  # Only useful for migration
	[[ -n "${DEST_HOST}" ]] && return 0  # Makes sense only for local migration
	[[ "${#CFG_CHANGED[@]}" -eq 0 ]] && return 0  # Skip emergency removal when allright was run

	local xml

	for xml in "${CFG_CHANGED[@]}"; do
		if mv "${xml}${CFG_BACKUP_EXT}" "${xml}"; then
			techo "Restored zone configuration file: ${xml}"
		else
			echo "Failed to restore zone configuration file: ${xml}" 1>&2
		fi
	done
}

_fix_zone_index() {
	local index="/etc/zones/index"
	local fix="s#/${UUID_SRC}:.*#/${UUID_SRC}:${UUID_SRC}#"
	local -a sed_cmd=("${SED}" -i ".fix-${TIME_STARTED}" -e "${fix}" "${index}")

	_dest_host_cmd "${sed_cmd[@]}" || die ${ERR_VM_XML} "Couldn't fix VM uuid in zone index: ${index}"
	techo "Fixed VM uuid in zone index: ${index}"
}

zone_attach() {
	# Makes sense only for remote migration
	[[ -z "${DEST_HOST}" ]] && return 0

	_dest_host_cmd _zone_create "${UUID_SRC}" "/${DS_ROOT#* }" || die ${ERR_VM_ATTACH} "Failed to initialize destination VM: ${UUID_SRC}"
	_dest_host_cmd _zone_attach "${UUID_SRC}" || die ${ERR_VM_ATTACH} "Failed to attach destination VM: ${UUID_SRC}"
	VM_ATTACHED="true"
	techo "Attached destination VM: ${UUID_SRC}"
	_fix_zone_index
}

zone_delete_err() {
	# Emergency zone removal on destination host (opposite of zone_attach)
	[[ "${MODE}" != "migrate" ]] && return 0  # Only useful for migration
	[[ -z "${DEST_HOST}" ]] && return 0  # Makes sense only for remote migration
	[[ -z "${VM_ATTACHED}" ]] && return 0  # Skip emergency removal when allright was run

	# shellcheck disable=SC2155
	local core_ds="$(_get_core_dataset "${DS_ROOT#* }")"

	if [[ -n "${VM_READY}" ]]; then
		# Live migration -> VM was started on destination host
		if _dest_host_cmd "_vm_stop_force" "${UUID_SRC}"; then
			VM_READY=""
			techo "Stopped destination VM: ${UUID_SRC}"
		else
			echo "Failed to stop destination VM: ${UUID_SRC}" 1>&2
		fi
	fi

	if _dest_host_cmd _zone_delete "${UUID_SRC}"; then  # This should also remove the entry from zone index file
		_dest_host_cmd "${ZFS}" destroy "${core_ds}"  # Also silently remove cores dataset
		VM_ATTACHED=""
		techo "Removed destination VM: ${UUID_SRC}"
	else
		echo "Failed to remove destination VM: ${UUID_SRC}" 1>&2
	fi
}

_init_core_dataset() {
	local dataset="$1"
	local mountpoint="$2"

	${ZFS} create -p -o quota=${CORE_QUOTA}m -o mountpoint="${mountpoint}" "${dataset}"
}

init_core_dataset() {
	# Needed when migrating on new zpool
	[[ -z "${DS_ROOT}" ]] && return 0

	local dst="${DS_ROOT#* }"
	local pool="${dst%%/*}"
	local dataset="${pool}/cores"
	local mountpoint="/${pool}/global/cores"

	if _dest_host_cmd _zfs_dataset_exists "${dataset}" &> /dev/null; then
		techo "Global cores dataset exists: ${dataset}"
	else
		_dest_host_cmd _init_core_dataset "${dataset}" "${mountpoint}" || \
			die ${ERR_DS_CORE} "Could not initialize global cores dataset: ${dataset}"
		techo "Initialized global cores dataset: ${dataset}"
	fi
}

create_core_dataset() {
	# Makes sense for local migration and when root pool has changed
	# In remote migration the cores dataset is created by zone_attach,
	# except for LX zones -> we need to create the cores dataset manually
	[[ -z "${DS_ROOT}" ]] && return 0
	[[ -n "${DEST_HOST}" && -z "${VM_CORES_RM}" ]] && return 0

	local dst="${DS_ROOT#* }"
	# shellcheck disable=SC2155
	local core_ds="$(_get_core_dataset "${dst}")"

	if _dest_host_cmd _zfs_dataset_exists "${core_ds}" &> /dev/null; then
		techo "Cores dataset exists: ${core_ds}"
	else
		_dest_host_cmd _create_core_dataset "${core_ds}" "/${dst}/cores" || \
			die ${ERR_DS_CORE} "Could not create cores dataset: ${core_ds}"
		techo "Created cores dataset: ${core_ds}"
	fi
}

_destroy_dataset() {
	local dataset="$1"
	local target="${2:-"source"}"

	if _zfs_destroy "${dataset}" "true"; then  # true means recursive force destroy
		techo "Destroyed ${target} dataset: ${dataset}"
	else
		echo "Could not destroy ${target} dataset: ${dataset}" 1>&2
	fi
}

destroy_datasets_dst_err() {
	# Emergency cleanup of sent/received datasets. WARNING: Use with care!
	# (opposite of send_recv_datasets*)
	local dst

	[[ "${MODE}" != "migrate" ]] && return 0  # Only useful for migration
	[[ "${#DS_RECV[@]}" -eq 0 ]] && return 0  # Skip emergency cleanup when allright was run

	for dst in "${DS_RECV[@]}"; do
		_dest_host_cmd _destroy_dataset "${dst}" "destination"
	done

	DS_RECV=()
}


###############################################################
# stage 4: live migration
###############################################################

live_migration() {
	[[ -z "${VM_STOP}" && "${VM_STATUS_SRC}" == "running" ]]
}

remove_kvm_mem_dump() {
	[[ -z "${VM_MEM_DUMP}" ]] && return 0

	if _dest_host_cmd rm -f "${VM_TMP_MEM_FILE}"; then
		techo "Removed memory dump ${VM_TMP_MEM_FILE} on ${DEST_HOST}"
		VM_MEM_DUMP=""
	else
		echo "Failed to remove memory dump ${VM_TMP_MEM_FILE} on ${DEST_HOST}" 1>&2
	fi

	# We will also clean other memory dumps /var/tmp from older failed migrations
	# (on both, source and destination host)
	techo "Removing old memory dumps in ${TMP_DIR} on localhost"
	find "${TMP_DIR}" -type f -name "*.${VM_MEM_FILE_SUFFIX}.*" -mmin +120 -exec rm -f "{}" \;
	techo "Removing old memory dumps in ${TMP_DIR} on ${DEST_HOST}"
	_dest_host_cmd find "${TMP_DIR}" -type f -name "*.${VM_MEM_FILE_SUFFIX}.*" -mmin +120 -exec rm -f "{}" \;
}

resume_vm_err() {
	# Emergency resume of source VM (called from cleanup)
	[[ -z "${VM_RESUME}" ]] && return 0

	local zone_root_src="${DS_ROOT%% *}"
	local qmp_socket="/${zone_root_src}/root${VM_QMP_SOCK}"

	echo "Uh-oh, live migration has failed; resuming source VM: ${UUID_SRC} ..." 1>&2

	if _vm_qmp_cmd "${qmp_socket}" "migrate-cancel" > /dev/null; then
		techo "Cancel live migration on source VM: ${UUID_SRC}"
	else
		echo "Failed to cancel live migration on source VM: ${UUID_SRC}" 1>&2
	fi

	if _vm_qmp_cmd "${qmp_socket}" "cont" > /dev/null; then
		VM_RESUME=""
		techo "Resumed source VM: ${UUID_SRC}"
	else
		echo "Failed to resume source VM: ${UUID_SRC}" 1>&2
	fi
}

# This is a background process identified by VM_DISK_TRANSFER_PID
_transfer_kvm_disk() {
	local running="true"
	local -i rc=0
	local stdout

	trap "running=''" USR1

	while [[ -n "${running}" ]]; do
		stdout="$(send_recv_zvols_incr)"
		rc=$?

		if [[ -n "${stdout}" && -n "${VERBOSE}" ]]; then
			if [[ "${VERBOSE}" -eq 1 ]]; then
				echo -ne "."
			else
				echo "${stdout}"
			fi
		fi

		sleep 0.5
	done

	return ${rc}
}

# This should never happen, because _transfer_kvm_disk will be interrupted by _wait_send_recv_kvm_ram_and_disk
transfer_kvm_disk_err() {
	[[ -z "${VM_DISK_TRANSFER_PID}" ]] && return 0

	echo "Killing disk transfer background process" 1>&2
	kill "${VM_DISK_TRANSFER_PID}"
}

# This is a background process identified by VM_MEM_TRANSFER_PID
_transfer_kvm_ram() {
	local migration_socket="${1}"

	rm -f "${migration_socket}"
	"${SOCAT}" -u UNIX-LISTEN:"${migration_socket}" - | run_ssh "root@${DEST_HOST}" -- "umask 0277; ${CAT} > ${VM_TMP_MEM_FILE}"
}

transfer_kvm_ram_err() {
	[[ -z "${VM_MEM_TRANSFER_PID}" ]] && return 0

	echo "Killing memory transfer background process" 1>&2
	kill "${VM_MEM_TRANSFER_PID}"
}

# This loop waits for socat process to exit (meaning end of RAM transfer)
_wait_send_recv_kvm_ram_and_disk() {
	local -i socat_rc=0
	local -i sendrecv_rc=0

	while [[ -n ${VM_MEM_TRANSFER_PID} ]] && check_pid "${VM_MEM_TRANSFER_PID}"; do
		techo "Waiting for memory transfer to finish ..."
		wait "${VM_MEM_TRANSFER_PID}"
		socat_rc=$?
		break
	done

	VM_MEM_TRANSFER_PID=""

	start_downtime

	while [[ -n ${VM_DISK_TRANSFER_PID} ]] && check_pid "${VM_DISK_TRANSFER_PID}"; do
		techo "Waiting for disk transfer to finish ..."
		kill -USR1 "${VM_DISK_TRANSFER_PID}"
		wait "${VM_DISK_TRANSFER_PID}"
		sendrecv_rc=$?
		break
	done

	VM_DISK_TRANSFER_PID=""

	[[ "${socat_rc}" -eq 0 && "${sendrecv_rc}" -eq 0 ]]
}

send_kvm_ram() {
	local zone_root_src="${DS_ROOT%% *}"
	local qmp_socket="/${zone_root_src}/root${VM_QMP_SOCK}"
	local migration_socket="/${zone_root_src}/root${VM_MIGRATION_SOCK}"
	local migration_status

	techo "Creating and sending memory dump to ${VM_TMP_MEM_FILE} on ${DEST_HOST} ..."

	# Transfer socat must be running before we issue the migrate command to QMP
	_transfer_kvm_ram "${migration_socket}" &
	VM_MEM_TRANSFER_PID=$!

	if check_pid "${VM_MEM_TRANSFER_PID}"; then
		VM_MEM_DUMP="true"
	else
		die ${ERR_VM_MEM_SENDRECV} "Memory transfer did not start"
	fi

	# Start live migration
	if _vm_qmp_cmd "${qmp_socket}" "migrate" "unix:${VM_MIGRATION_SOCK}" > /dev/null; then
		VM_RESUME="true"
	else
		die ${ERR_VM_MEM_SENDRECV} "Memory dump failed"
	fi

	# Run send_recv_zvols_incr in an never-ending loop
	_transfer_kvm_disk &
	VM_DISK_TRANSFER_PID=$!

	# Wait for migration to finish + stop _transfer_kvm_disk background process
	if _wait_send_recv_kvm_ram_and_disk; then
		techo "Memory transfer finished -> source VM is paused now"
	else
		die ${ERR_VM_MEM_SENDRECV} "Memory or disk transfer failed"
	fi

	# Migration has finished -> VM is paused now
	migration_status="$(_vm_qmp_cmd "${qmp_socket}" "query-migrate")"

	# shellcheck disable=SC2181
	if [[ $? -eq 0 && "${migration_status}" == "completed" ]]; then
		techo "Memory transfer finished correctly -> source VM is paused now"
	else
		die ${ERR_VM_MEM_SENDRECV} "Bad migration status on source VM: ${migration_status}"
	fi
}

recv_kvm_ram() {
	local zone_root_dst="${DS_ROOT#* }"
	local qmp_socket="/${zone_root_dst}/root${VM_QMP_SOCK}"
	local migration_socket="/${zone_root_dst}/root${VM_MIGRATION_SOCK}"

	techo "Starting destination VM: ${UUID_SRC} ..."

	if _dest_host_cmd "_vm_start" "${UUID_SRC}" > /dev/null; then
		VM_READY="true"
		techo "Started destination VM: ${UUID_SRC}"
	else
		die ${ERR_VM_START} "Failed to start destination VM: ${UUID_SRC}"
	fi

	techo "Loading memory dump to VM ${UUID_SRC} from ${VM_TMP_MEM_FILE} on ${DEST_HOST} ..."

	if _dest_host_cmd "${SOCAT}" -u "OPEN:${VM_TMP_MEM_FILE}" "UNIX-CONNECT:${migration_socket},retry=30,interval=0.5"; then
		techo "Memory dump successfully loaded"
	else
		die ${ERR_VM_MEM_SENDRECV} "Failed to load memory dump"
	fi

	techo "Checking destination VM: ${UUID_SRC}"

	if _dest_host_cmd _vm_qmp_cmd "${qmp_socket}" "is-running" > /dev/null; then
		VM_RESUME=""  # We are good here -> info for emergency cleanup
		stop_downtime
		techo "Successfully resumed destination VM: ${UUID_SRC}"
	else
		echo "ERROR: Unexpected problem with destination VM: ${UUID_SRC}" 1>&2
		# Debug info
		_dest_host_cmd "${SED}" -ne '/^=== OUTPUT/,//p' "/${zone_root_dst}/root/tmp/vm.log" 1>&2
		die ${ERR_VM_MEM_SENDRECV} "Failed to resume destination VM: ${UUID_SRC}"
	fi
}

fix_vm_properties_dst() {
    local zone_root_dst="${DS_ROOT#* }"
	local migration_socket="/${zone_root_dst}/root${VM_MIGRATION_SOCK}"

	if _dest_host_cmd _vm_update "${UUID_SRC}" qemu_extra_opts="${VM_QEMU_OPTS_SRC}" &> /dev/null; then
		techo "Restored configuration of destination VM: ${UUID_SRC}"
	else
		die ${ERR_VM_XML} "Failed to restore configuration of destination VM: ${UUID_SRC}"
	fi

	# Although we have removed the QEMU migration parameter, the migration socket still exits
	# -> this would break next live migration
	if _dest_host_cmd rm -f "${migration_socket}"; then
		techo "Removed migration socket of destination VM: ${UUID_SRC}"
	fi
}


###############################################################
# stage 4: after checks
###############################################################

_check_vm() {
	local uuid="$1"
	# shellcheck disable=SC2155
	local out=$(_dest_host_cmd _vm_start "${uuid}" && _dest_host_cmd _vm_stop_force "${uuid}")

	# shellcheck disable=SC2181
	[[ $? -ne 0 || "${out}" != *"Successfully started"* ]] && \
		die ${ERR_VM_AFTER_CHECK} "Transferred VM could not be started!"
	techo "VM is able to start: ${uuid}"
}

check_vm_migrate() {
	_check_vm "${UUID_SRC}"
}


###############################################################
# stage 5: remove source datasets/VM, remove helper snapshots on target
###############################################################

destroy_snapshots_dst() {
	# Remove migration snapshots on destination datasets
	if [[ "${#DS_RECV[@]}" -ne 0 && "${#SNAPSHOTS[@]}" -ne 0 ]]; then
		for dst in "${DS_RECV[@]}"; do
			# Destroy all snapshots created after first esmigrate snapshot!
			_dest_host_cmd _destroy_snapshot "${dst}@${SNAPSHOTS[0]}%" "destination"
		done
	fi
}

_remove_indestructible() {
	local uuid="$1"

	if _vm_property "${JSON_SRC}" "indestructible_zoneroot" &> /dev/null; then
		techo "Removing indestructible properties from VM datasets"
		_vm_remove_indestructible_property "${uuid}" &>/dev/null
	fi
}

_delete_vm() {
	local uuid="$1"

	_remove_indestructible "${uuid}"

	# we cannot use "vmadm destroy" because it refuses to destroy a detached VM
	_zone_delete "${uuid}" > /dev/null

	# shellcheck disable=SC2181
	if [[ $? -eq 0 ]]; then
		techo "Destroyed source VM: ${uuid}"
	else
		echo "Failed to destroy source VM: ${uuid}" 1>&2
	fi
}

destroy_datasets_src() {
	# Cleanup all source datasets, that are unused
	[[ "${MODE}" != "migrate" ]] && return 0  # Only useful for migration

	local ds_root
	local ds_data

	_remove_indestructible "${UUID_SRC}"

	if live_migration && [[ -n "${DEST_HOST}" ]]; then
		# - apply delete only to remote migration
		# - we need to get src VM to detached state before datasets removal
		techo "Halting source VM"
		_zone_halt "${UUID_SRC}"

		# core dataset can be destroyed only after VM stop
		set_vm_status_src	# re-read VM state
		destroy_core_dataset

		techo "Detaching source VM"
		_zone_detach "${UUID_SRC}"
	fi

	# remove migrated source datasets
	if [[ -n "${DS_ROOT}" ]]; then
		ds_root=${DS_ROOT%% *}
		_destroy_dataset "${ds_root}"
		if [[ -z "${DEST_HOST}" ]]; then  # local migration
			# Destroy source cores dataset in local migration and when root pool has changed
			_destroy_dataset "$(_get_core_dataset "${ds_root}")"
		fi
	fi

	# The OS zone delegated dataset is a child and destroyed together with the DS_ROOT
	if [[ "${#DS_DATA[@]}" -ne 0 ]] && is_kvm; then
		for ds_data in "${DS_DATA[@]}"; do
			_destroy_dataset "${ds_data%% *}"
		done
	fi

	if [[ -n "${DEST_HOST}" ]]; then  # remote migration -> remove also source VM
		_delete_vm "${UUID_SRC}"
	fi

	DS_RECV=()
	# This will disable destroy_snapshots in cleanup
	SNAPSHOTS=()
}

vminfod_restart() {
	local service_name=""

	# check compatibility with older esmigrate clients
	if remote_function_exists _vminfod_restart; then
		service_name="vminfod"
	else
		techo "Info: the remote side has v3.0.0 or older"
		service_name="vmadmd"
	fi

	if _dest_host_cmd "_${service_name}_restart"; then
		techo "Restarted ${service_name}"
	else
		echo "${service_name} restart failed" 1>&2
	fi
}

wait_for_vmadm_detect() {
	local timeout=180	# sec

	techo "Waiting for VM to become visible by vmadm"

	# check compatibility with older esmigrate clients
	if remote_function_exists _vm_wait_for_become_visble; then
		if _dest_host_cmd _vm_wait_for_become_visble "${UUID_SRC}" "${timeout}"; then
			techo "VM is present"
		else
			die ${ERR_VM_AFTER_CHECK} "Transferred VM was not detected by vminfod!"
		fi
	else
		# older clients must just wait
		sleep 10
	fi
}

_start_vm() {
	[[ -z "${VM_START}" ]] && return 1

	local uuid="$1"
	local target="${2:-"source"}"
	local -a cmd

	if [[ "${target}" == "destination" ]]; then
		cmd=("_dest_host_cmd" "_vm_start" "${uuid}")
	else
		cmd=("_vm_start" "${uuid}")
	fi

	if "${cmd[@]}" > /dev/null; then
		VM_START=""
		stop_downtime
		techo "Started ${target} VM: ${uuid}"
	else
		echo "Failed to start ${target} VM: ${uuid}" 1>&2
	fi
}

start_vm_migrate() {
	_start_vm "${UUID_SRC}" "destination"
}

start_vm_err() {
	_start_vm "${UUID_SRC}" "source"
}


###############################################################
# stage 6: all done
###############################################################

allright() {
	DS_RECV=()		# Clear the need for emergency target datasets removal
	CFG_CHANGED=()	# Clear the need for emergency config file restore
	VM_ATTACHED=""	# Clear the need for emergency destination VM removal
	VM_DETACHED=""	# Clear the need for emergency source VM attach
	VM_DETACHED_FAKE=""	# Clear the need for emergency source VM fake-attach
	VM_CORES_RM=""	# Clear the need for emergency re-creation of source VM's cores dataset
	VM_RESUME=""	# Clear the need for emergency resume of source VM
	VM_MEM_TRANSFER_PID=""	# Clear the need for killing a running _transfer_kvm_ram background process
	VM_DISK_TRANSFER_PID=""	# Clear the need for killing a running _transfer_kvm_disk background process
}

print_json() {
	[[ -z "${PRINT_JSON}" ]] && return 0

	# shellcheck disable=SC2155
	local j=$(_dest_host_cmd _vm_json "${UUID_SRC}")

	echo "${j}"
}

success() {
	[[ -n "${VERBOSE}" ]] && echo

	# shellcheck disable=SC2155
	local -i time_ended=$(get_timestamp)
	local -i time_elapsed=$((time_ended - TIME_STARTED))
	local rate="sent ${SIZE} bytes in ${time_elapsed} seconds"

	if [[ ${DOWNTIME} -ne 0 ]]; then
		rate+="; with ${DOWNTIME} seconds of VM downtime"
	fi

	echo "Successfully migrated VM ${UUID_SRC} (${rate})"
}

cleanup() {
	# Emergency stuff (will run only if allright was not run)
	transfer_kvm_disk_err
	transfer_kvm_ram_err
	update_zone_xml_err
	zone_attach_err
	create_core_dataset_err
	zone_delete_err
	destroy_datasets_dst_err
	start_vm_err
	resume_vm_err

	# General cleanup (will always run)
	remove_kvm_mem_dump
	destroy_snapshots
}


###############################################################
# input validators
###############################################################

validate_input_migrate() {
	if [[ -z "${DEST_HOST}" ]]; then  # local
		if is_kvm; then
			# local migration of KVM machine's disk(s) into another pool
			# and/or local migration of KVM machine's root pool into another pool
			[[ ${#DEST_DISK[@]} -eq 0 && -z "${DEST_POOL}" ]] && \
				die ${ERR_INPUT} "Missing target disk pool parameter and/or target zone pool parameter"
			[[ -z "${VM_STOP}" ]] && die ${ERR_INPUT} "Live migration cannot be performed locally"
		else
			# local migration of OS zone into another pool
			[[ ${#DEST_DISK[@]} -ne 0 ]] && die ${ERR_INPUT} "Redundant target disk pool parameter"
			[[ -z "${DEST_POOL}" ]] && die ${ERR_INPUT} "Missing target zone pool parameter"
			[[ -z "${VM_STOP}" ]] && die ${ERR_INPUT} "Live migration is currently available only for KVM"
		fi
	else  # remote
		if is_kvm; then
			# migrate KVM machine on to another host (all or none parameters can be used)
			[[ -z "${VM_STOP}" && "${VM_STATUS_SRC}" != "running" ]] && \
				die ${ERR_INPUT} "Live migration is possible only when source VM is in running state"
		else
			# migrate whole OS zone on to another host (only target pool can be used)
			[[ ${#DEST_DISK[@]} -ne 0 ]] && die ${ERR_INPUT} "Redundant target disk pool parameter"
			[[ -z "${VM_STOP}" ]] && die ${ERR_INPUT} "Live migration is currently available only for KVM"
		fi
	fi
}


###############################################################
# main
###############################################################

set_opts() {
	local opt

	DEST_HOST=""
	DEST_POOL=""
	DEST_DISK=()

	while getopts "vLjC:H:p:0:1:2:3:4:5:6:7:" opt; do
		case "${opt}" in
			v)
				if [[ -z "${VERBOSE}" ]]; then
					VERBOSE=1
				else
					((VERBOSE++))
				fi
				;;
			C)
				validate_int "${OPTARG}" "Invalid VNC port"
				[[ "${OPTARG}" -le 1024 || "${OPTARG}" -ge 65535 ]] && die ${ERR_INPUT} "Invalid VNC port"
				VM_VNC_PORT="${OPTARG}"
				;;
			L)
				VM_STOP=""
				;;
			j)
				PRINT_JSON="true"
				;;
			H)
				validate_ascii "${OPTARG}" "Invalid target host name or IP address"
				DEST_HOST="${OPTARG}"
				;;
			p)
				validate_ascii "${OPTARG}" "Invalid target root pool"
				DEST_POOL="${OPTARG}"
				;;
			[0-8])
				validate_ascii "${OPTARG}" "Invalid target disk pool or disk ID"
				DEST_DISK[${opt}]="${OPTARG}"
				;;
			*)
				die ${ERR_INPUT}
				;;
		esac
	done
}

migrate() {
	UUID_SRC="${1:-}"
	shift

	# stage 1
	validate_uuid "${UUID_SRC}"
	set_opts "${@-}"			# Prepare ${DEST_HOST}, ${DEST_POOL} and ${DEST_DISK}
	set_vm_status_src			# Set ${VM_STATUS_SRC}
	set_vm_json_src				# Set ${JSON_SRC}
	set_vm_brand_src			# Set ${VM_BRAND_SRC}
	set_vm_properties_src		# Set ${VM_QEMU_OPTS_SRC} (required for live migration)
	validate_dest_host_ssh		# Check if remote host is reachable
	validate_input_migrate		# Advanced input validation
	set_datasets_migrate		# Prepare ${DS_ROOT} and ${DS_DATA}
	validate_dest_host_migrate	# Check remote host free space, pools, nic_tags, ...
	validate_kvm_qmp			# Check if QMP socket is alive (required for live migration)
	verbose_stage1				# Print ${DS_ROOT} and ${DS_DATA}

	# stage 2
	set_vm_status_src			# Set ${VM_STATUS_SRC} ("double check")
	destroy_core_dataset		# Destroy cores dataset when doing remote migration and VM is stopped
	zone_detach					# Detach zone when doing remote migration and VM is stopped
	send_recv_datasets_init		# Create snapshots (+ aggregate snapshot size) + Full zfs send/recv
	send_recv_datasets_incr		# Create snapshots (+ aggregate snapshot size) + First incremental zfs send/recv

	# stage 2.5 (skipped when doing live migration)
	if stop_vm; then			# Stop VM if running, or keep running if requested by user
		destroy_core_dataset	# Destroy cores dataset when doing remote migration and VM is stopped
		zone_detach				# Detach zone when doing remote migration and VM is stopped
		send_recv_datasets_incr	# Create snapshots (+ aggregate snapshot size) + Final incremental zfs send/recv
	fi

	# stage 3
	update_zone_xml				# Update zone configuration file
	init_core_dataset			# Ensure that global cores dataset exists
	zone_attach					# Attach zone on remote host when doing remote migration
	create_core_dataset			# Create cores dataset when changing root pool locally or doing remote migration
	vminfod_restart				# Restart vminfod to ensure detection of transferred VM's presence
	wait_for_vmadm_detect		# Wait for dest VM to become visible by vmadm

	# stage 4 (live migration + checks)
	check_vm_migrate			# Check if migrated destination VM can be started

	if live_migration; then
		send_kvm_ram			# Start memory transfer + pause VM
		send_recv_zvols_incr	# Create snapshots (+ aggregate snapshot size) + Final incremental zfs send/recv
		recv_kvm_ram			# Start destination VM + load transferred memory + resume destination VM
		fix_vm_properties_dst	# Restore destination VM configuration to normal (qemu_extra_opts)
	fi

	# stage 5
	destroy_snapshots_dst		# Remove migration snapshots on target host
	destroy_datasets_src		# Remove source datasets which are not needed anymore

	if ! live_migration; then
		start_vm_migrate		# Start destination VM if the source VM was shutdown during migration
	fi

	# stage 6
	allright					# Turn off emergency cleanup stuff
	cleanup						# Remove snapshots
	success						# Print success message
	print_json					# Print VM json to stdout (if -j parameter is specified)
}

main() {
	MODE=${1-}

	case "${MODE}" in
		migrate)
			trap cleanup EXIT	# Enable emergency cleanup
			shift
			${MODE} "${@-}"
			exit ${OK}
			;;
		agent|agent-verbose)
			[[ "${MODE}" == *"verbose" ]] && VERBOSE=1
			shift
			"${@-}"
			exit $?
			;;
		-h|--help)
			usage
			exit ${OK}
			;;
		*)
			usage
			exit ${ERR_INPUT}
			;;
	esac
}

main "${@}"
