#!/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 on server.
EOF
}


upload_image() {
    # check if VM-Diskimage exists
    if [[ ! (-f "${VM_SYSDIR}/${VM_NAME}.qcow2" || -f "${VM_DIR}/${VM_NAME}.qcow2") ]]; then
        echo "File not found ${VM_NAME}.qcow2" >&2
        exit 1
    fi
    vm-aria2 stop "${VM_NAME}" || echo "VMImage-torrent not running"
    # link private VM-Diskimage to system-Dir
    if [[ -f "${VM_DIR}/${VM_NAME}.qcow2" \
          &&   ( -f "${VM_SYSDIR}/${VM_NAME}.qcow2" && ("${VM_DIR}/${VM_NAME}.qcow2" -nt "${VM_SYSDIR}/${VM_NAME}.qcow2") \
          || ! -f "${VM_SYSDIR}/${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" "${VM_SYSDIR}/${VM_NAME}.qcow2"
    fi
    cd "${VM_SYSDIR}"
    if [[ -f "/tmp/${VM_NAME}.qcow2.torrent" ]]; then
      rm -f "/tmp/${VM_NAME}.qcow2.torrent"
    fi
    uploadseed --server "${SEEDBOX_HOST}:${SEEDBOX_RPC_PORT}" --dht-port "${SEEDBOX_PORT}" \
	       --pwdfile "${SEEDBOX_PWFILE}" --no-cert "${VM_NAME}.qcow2"
}

source /etc/lmn/vm.conf

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

shift "$((OPTIND -1))"

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

VM_NAME=$1

upload_image
