#!/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
      echo "No torrent-File found"
      exit 1
    fi
    lockfile="/tmp/sync-vm-${VM_NAME}.lock"
    if ! flock -n "$lockfile" echo "try to acquire lock"; then
      echo torrent seems to be in process.
      echo waiting for completion ...
      flock -w 3600 "$lockfile" echo "...completed"
      sleep 5
    else
      (
        if ! flock -n 200; then
	  echo "failed to acquire lock"
	  echo "Bitte noch einmal starten."
          echo "Beliebige Taste zum Beenden."
	  read -n 1
	  exit 1
        fi
        torrent="${VM_NAME}.qcow2.torrent"
        session="${torrent//./_}"
        if vmimage-torrent status | grep -qw ^"$session"; then
          vmimage-torrent stop "${VM_NAME}.qcow2"
        fi
        cd /lmn/vm
        ctorrent -e 0 "${VM_NAME}.qcow2.torrent"
        /usr/local/bin/vmimage-torrent restart "${VM_NAME}.qcow2"
        if ! flock -u 200; then
	  echo failed to drop lock
	  exit 1
	fi
      ) 200>"$lockfile"
    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/
}

delete_old_qcows() {
    cd /lmn/vm
    for qcow2 in $(find . -maxdepth 1 -name "*.qcow2" -exec basename {} ';'); do
	qcowsize=$(stat -c%s "${qcow2}")
	if [[ -f "${qcow2}.size" ]] && [[ "${qcowsize}" != $(<"${qcow2}.size") ]]; then
            torrent="${qcow2}.torrent"
            session="${torrent//./_}"
            if vmimage-torrent status | grep -qw ^"$session"; then
                vmimage-torrent stop "${qcow2}"
            fi
            mv "${qcow2}" /tmp/
	fi
    done
}

sync_all_torrents() {
    rsync -ai rsync://server:/vmimages-download/*.torrent /lmn/vm/
    rsync -ai rsync://server:/vmimages-download/*.size /lmn/vm/
    delete_old_qcows
    rsync -ai rsync://server:/vmimages-download/*.xml /lmn/vm/
    RSYNC_COMMAND=$(rsync -ai --delete --exclude=mimeinfo.cache rsync://server:/vmimages-download/desktop/ /usr/local/share/applications/ | sed '/ \.\//d')
    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
