#!/usr/bin/bash
# Push VM-Disk-Image on server
set -eu

show_help() {
    cat << EOF >&2
Usage: $(basename "$0") vmname"
Create torrent and upload disk, torrent and xml-VM-Definiton on server.
EOF
}

VM_DIR="/tmp/${SUDO_UID}/vm"

upload_image() {
    # check if VM-Diskimage exists
    if [[ ! (-f "/lmn/vm/${VM_NAME}.qcow2" || -f "${VM_DIR}/${VM_NAME}.qcow2") ]]; then
        echo "File not found ${VM_NAME}.qcow2" >&2
        exit 1
    fi
    # check if VM-Machine-Definition XML exists
    if [[ ! (-f "/lmn/vm/${VM_NAME}.xml" || -f "${VM_DIR}/${VM_NAME}.xml") ]]; then
        echo "File not found ${VM_NAME}.xml" >&2
        exit 1
    fi
    sudo -u lmnsynci /usr/local/bin/vmimage-torrent stop "${VM_NAME}.qcow2" || echo "VMImage-torrent not running"
    # link private VM-Diskimage to system-Dir
    if [[ -f "${VM_DIR}/${VM_NAME}.qcow2" \
          &&   ( -f "/lmn/vm/${VM_NAME}.qcow2" && ("${VM_DIR}/${VM_NAME}.qcow2" -nt "/lmn/vm/${VM_NAME}.qcow2") \
          || ! -f "/lmn/vm/${VM_NAME}.qcow2") ]]; then
      echo "copy private VM-Diskimage to system-dir"
      chown lmnsynci:lmnsynci "${VM_DIR}/${VM_NAME}.qcow2"
      ln -f "${VM_DIR}/${VM_NAME}.qcow2" "/lmn/vm/${VM_NAME}.qcow2"
    fi
    # copy private VM-Maschine-Definition XML to system-Dir
    if [[ -f "${VM_DIR}/${VM_NAME}.xml" \
          &&   ( -f "/lmn/vm/${VM_NAME}.xml" && $(cmp -s "${VM_DIR}/${VM_NAME}.xml" "/lmn/vm/${VM_NAME}.xml") \
          || ! -f "/lmn/vm/${VM_NAME}.xml") ]]; then
      echo "copy private VM-Maschine-Definition XML to system-dir"
      chown lmnsynci:lmnsynci "${VM_DIR}/${VM_NAME}.xml"
      cp -a "${VM_DIR}/${VM_NAME}.xml" "/lmn/vm/"
    fi
    cd /lmn/vm
    # (re-) create torrent file
    sudo -u lmnsynci /usr/local/bin/vmimage-torrent create "${VM_NAME}.qcow2"
    # create size-information-file
    stat -c%s "${VM_NAME}.qcow2" > "${VM_NAME}.qcow2.size"
    chown lmnsynci:lmnsynci "${VM_NAME}.qcow2.size"
    # Upload Torrent, qcow2 and machine-definition-XML
    [[ -f "/lmn/vm/${VM_NAME}.qcow2.torrent" ]] && rsync -av --password-file=/etc/rsync.secret \
	  "/lmn/vm/${VM_NAME}.qcow2.torrent" rsync://vmuser@server:/vmimages-upload/
    rsync -av --password-file=/etc/rsync.secret "/lmn/vm/${VM_NAME}.qcow2.size" \
	  rsync://vmuser@server:/vmimages-upload/
    rsync -av --password-file=/etc/rsync.secret "/lmn/vm/${VM_NAME}.qcow2" \
	  rsync://vmuser@server:/vmimages-upload/
    rsync -av --password-file=/etc/rsync.secret "/lmn/vm/${VM_NAME}.xml" \
	  rsync://vmuser@server:/vmimages-upload/
}

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

VM_NAME=$1

upload_image
