#!/bin/bash

SRC_FILE="$1"
DEST_VM="$2"

QEMUBIN="/opt/erigones/bin/qemu-img"

if [[ -z "${SRC_FILE}" ]] || [[ -z "${DEST_VM}" ]]; then
cat << EOF
This script converts and imports virtual disks in various source formats
(e.g. vmdk, raw, qcow2, ...) into specified local virtual machine.
The first attached disk of the destination VM will be overwritten.

Usage:   $0 <image_file> <dest_vm_alias>
Example: $0 disk1.vmdk mynewvm.lan

EOF
	exit 1
fi

if [[ ! -e "${SRC_FILE}" ]]; then
	echo "ERROR: Source file does not exist!"
	exit 2
fi

DEST_VM_UUID="$(vmadm list -H -o uuid hostname="${DEST_VM}")"
if [[ -z "${DEST_VM_UUID}" ]]; then
	echo "ERROR: Virtual machine ${DEST_VM} does not seem to exist on this host!"
	exit 2
fi

echo
echo "*** SOURCE DISK INFO ***"
${QEMUBIN} info "${SRC_FILE}"
echo "*** SOURCE DISK INFO END ***"
echo
echo "Destination VM alias: ${DEST_VM}"
echo "Destination VM UUID: ${DEST_VM_UUID}"
echo
echo "PLEASE, USE THE DESTINATION DISK EQUAL OR GREATER THAN THE SOURCE IMAGE SIZE."
echo
echo
if ! zfs list -Ho name  "zones/${DEST_VM_UUID}-disk0" > /dev/null 2>&1; then
	echo "ERROR: Virtual machine ${DEST_VM} does not seem to have any disk attached!"
	exit 3
fi


VM_DISK_DEV="/dev/zvol/rdsk/zones/${DEST_VM_UUID}-disk0"
echo "File ${SRC_FILE} will be converted and written to file ${VM_DISK_DEV}."
echo "Data on destination disk will be overwritten."
echo

# usage: if check_reply_yes "Some question?"; then echo yes; else echo no; fi
function check_reply_yes()
{
	echo -n "*** $1 (Y/n)"
	read -r reply
	if [[ -z "${reply}" ]] || [[ "${reply}" == "y" ]] || [[ "${reply}" == "Y" ]]
	then
		return 0
	else
		return 1
	fi
}

if check_reply_yes "Continue?"; then
	echo "Converting..."
	${QEMUBIN} convert -p -O host_device "${SRC_FILE}" "${VM_DISK_DEV}"
else
	echo "Exiting without change."
fi

