#!/usr/bin/bash
# Rebase one level down
set -eu

show_help() {
    cat << EOF >&2
Usage: $(basename "$0") [-n newname] vmname"
This script takes as input the name of the VM to rebase one level down
    -n   new name of the rebased image
EOF
}

source /etc/lmn/vm.conf

while getopts ':n:p' OPTION; do
  case "$OPTION" in
    n)
      NEWNAME=$OPTARG
      ;;
    p)
      VM_DIR="${VM_DIR_PERSISTENT}"
      ;;
    ?)
      show_help
      exit 1
      ;;
  esac
done

shift "$((OPTIND -1))"

# if less or more than one arguments supplied, display usage
if [[  $# -ne 1 ]]; then
    show_help
    exit 1
fi

# change to Images directory
cd "${VM_DIR}"

VM_NAME="$1"

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

# check if new VM-Diskimage exists
if [[ -v NEWNAME ]] && [[ -f "${NEWNAME}.qcow2" ]]; then
    echo "New Base already exists: ${NEWNAME}.qcow2" >&2
    exit 1
fi

NUMBASES=$(qemu-img info --backing-chain "${VM_NAME}.qcow2" | grep -c image)
NEWBASE=$(qemu-img info --backing-chain "${VM_NAME}.qcow2" | grep image | head  -n 3 | tail -n 1 | cut -d' ' -f2)
CURRENTBASE=$(qemu-img info --backing-chain "${VM_NAME}.qcow2" | grep image | head  -n 2 | tail -n 1 | cut -d' ' -f2)

if [[ ! "${NUMBASES}" -ge 3 ]]; then
    echo "Image must have at least 2 backing-files" >&2
    exit 1
fi

# check if base Diskimage exists
if [[ ! -f "${NEWBASE}" ]] || [[ ! -f "${CURRENTBASE}" ]]; then
    echo "Backingfiles not found ${CURRENTBASE}, ${NEWBASE}" >&2
    exit 1
fi

# rebasing disk image
qemu-img rebase -f qcow2 -b "${NEWBASE}" -F qcow2 "${VM_NAME}.qcow2"
if [[ -v NEWNAME ]]; then
    NEWNAME="${NEWNAME}.qcow2"
else
    rm -f "${CURRENTBASE}"
    NEWNAME="${CURRENTBASE}"
fi

mv "${VM_NAME}.qcow2" "${NEWNAME}"
chmod a-w "${NEWNAME}"