#!/usr/bin/bash
# create 1st level-Clones

set -eu

source /etc/lmn/vm.conf
PERSISTENT=0

while getopts ':p' OPTION; do
  case "$OPTION" in
    p)
      PERSISTENT=1
      VM_DIR="${VM_DIR_PERSISTENT}"
      ;;
  esac
done

shift "$((OPTIND -1))"

# if less than two arguments supplied, display usage
if [[  $# -ne 2 ]]; then
    echo "This script takes as input the name of the VM to clone" >&2
    echo "Usage: $0 vm_name_orig vm_name_clone" >&2
    exit 1
fi

VM_NAME=$1
VM_CLONE=$2

# Create User-VM-Dir and link system VM-Images
[[ -d "${VM_DIR}" ]] || mkdir -p "${VM_DIR}"
if [[ "${PERSISTENT}" -eq 1 ]]; then
    sudo /usr/local/bin/vm-link-images -p
else
    sudo /usr/local/bin/vm-link-images
fi

# change to image-directory
cd "${VM_DIR}"

if [[ ! -f "${VM_NAME}.qcow2" ]]; then
    echo "qcow2 File does not exists." >&2
    exit 1
fi

qemu-img create -f qcow2 -F qcow2 -b "${VM_NAME}.qcow2" "${VM_NAME}-${VM_CLONE}.qcow2"
chmod a-w "${VM_NAME}-${VM_CLONE}.qcow2"
