#!/bin/bash

show_help() {
  cat << EOF
Usage: $0 COMMAND [ARGS...]

Commands:
  restart   Restarts Vlab VNC server. All current sessions will be disconnected.
  set-res RESOLUTION
            Sets VNC resolution. Available resolutions are:
            - 800x600, 1024x768, 1366x768, 1440x900, 1920x1080
            You can also use 1-5 to select a resolution.
EOF
}

vnc-restart() {
  if [ "$(id -u)" -ne 0 ]; then
    exec sudo systemctl restart vlab-vnc.service
  fi
  exec systemctl restart vlab-vnc.service
}

vnc-set-res() {
  local RES=""
  case "$1" in
    1|800*) RES="800x600";;
    2|1024*) RES="1024x768";;
    3|1366*) RES="1366x768";;
    4|1440*) RES="1440x900";;
    5|1920*) RES="1920x1080";;
    *) echo "Unknown resolution '$1'" >&2; exit 1;;
  esac
  if [ -z "$RES" ]; then
    echo "What resolution?" >&2
    exit 1
  fi
  USER="$(id -nu)"
  eval UHOME=~$USER
  : ${HOME:=$UHOME}
  mkdir -p "$UHOME/.vnc"
  echo "$RES" > "$UHOME/.vnc/geometry"
  echo "Successfully set resolution '$RES'. It will take effect after restarting VNC service."
  exit 0
}

if [ $# -eq 0 ]; then
  show_help
  exit 1
fi

case "$1" in
  -h|--help) show_help; exit 0;;
  restart|set-res) CMD="vnc-$1"; shift; "$CMD" "$@";;
  *) echo "Unknown command '$1'" >&2; exit 1;;
esac

exit 0
