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

show_help() {
    cat << EOF >&2
Usage: $(basename "$0") [-d] [-a] [-t] [vmnames]"
Images from vmnames-List will be synced from server. Default by torrent.
Using flag -d VMs will be synced by rsync
Using flag -a images from images.list and xml-directory will be synced from server.
Using flag -t all torrents and xml-VM-Definitions will be synced
EOF
}

download_image() {
    rsync -av "rsync://server:/vmimages-download/${VM_NAME}.qcow2" \
       /lmn/vm/
    rsync -av "rsync://server:/vmimages-download/${VM_NAME}.xml" \
       /lmn/vm/
    rsync -av "rsync://server:/vmimages-download/${VM_NAME}.qcow2.torrent" \
       /lmn/vm/
    /usr/local/bin/vmimage-torrent restart "${VM_NAME}.qcow2"
}

torrent_image() {
    if [[ -f "/lmn/vm/${VM_NAME}.qcow2.torrent" ]]; then
      cd /lmn/vm
      ctorrent -e 0 "${VM_NAME}.qcow2.torrent"
      /usr/local/bin/vmimage-torrent restart "${VM_NAME}.qcow2"
    else
      echo "No torrent-File found"
      exit 1
    fi
}

sync_all_images() {
    rsync -av --files-from=/lmn/vm/images.list \
	  rsync://server:/vmimages-download/ /lmn/vm/
    rsync -av rsync://server:/vmimages-download/*.xml \
	  /lmn/vm/
}

sync_all_torrents() {
    rsync -ai rsync://server:/vmimages-download/*.torrent /lmn/vm/
    rsync -ai rsync://server:/vmimages-download/*.xml /lmn/vm/
    RSYNC_COMMAND=$(rsync -ai --delete rsync://server:/vmimages-download/desktop/*.desktop /usr/local/share/applications/)
    if [[ $? -eq 0 ]] && [[ -n "${RSYNC_COMMAND}" ]]; then
        echo "${RSYNC_COMMAND}"
        update-desktop-database /usr/local/share/applications
    fi
}

create_starter() {
    if [[ ! -f "/usr/share/applications/VM_${VM_NAME}_starter.desktop" ]]; then 
        cat << EOF >"/usr/share/applications/VM_${VM_NAME}_starter.desktop"
[Desktop Entry]
Version=1.0
Type=Application
Name=VMstart: ${VM_NAME}
GenericName=VM starter ${VM_NAME}
Comment=Start VM ${VM_NAME}
#TryExec=konsole
Exec=/usr/local/bin/run-vm.sh ${VM_NAME}
Icon=clementine
Categories=VM;Engineering;
MimeType=image/vnd.dxf;
Keywords=design;VM;diagrams;graphics
Terminal=true
EOF
        update-desktop-database /usr/share/applications
    fi
}

if [[ "$(id -nu)" != "lmnsynci" ]]; then
    echo "$(basename "$0") must be run as lmnsynci user"
    show_help
    exit 1
fi

while getopts ':dat' OPTION; do
    case "$OPTION" in
        d)
            DOWNLOAD=1
            ;;
        a)
            sync_all_images
            exit 0
            ;;
        t)
            sync_all_torrents
            exit 0
            ;;
        ?)
            show_help
            exit 1
            ;;
    esac
done

shift "$((OPTIND -1))"

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

for VM_NAME in "$@"; do
  if [[ -v "DOWNLOAD" ]]; then
    echo "Downloading $VM_NAME"
    download_image
  else
    echo "Torrenting $VM_NAME"
    torrent_image
  fi
done