#!/usr/bin/env bash

# shellcheck disable=SC2312

main() (
  # shellcheck disable=SC2009
  ps aux | grep UTM.app/Contents/MacOS/UTM >/dev/null 2>&1 || (
    echo Need to start UTM
    open -a UTM
    sleep 5
  )

  VERB="$1"
  shift

  if [ "${VERB}" = "list" ]; then
    list "$@"
  elif [ "${VERB}" = "start" ]; then
    start "$@"
  elif [ "${VERB}" = "stop" ]; then
    stop "$@"
  elif [ "${VERB}" = "status" ]; then
    status "$@"
  elif [ "${VERB}" = "backup" ]; then
    backup "$@"
  elif [ "${VERB}" = "compress" ]; then
    compress "$@"
  elif [ "${VERB}" = "bounce" ]; then
    bounce "$@"
  else
    echo utm list\|start\|stop\|bounce
  fi
)

compress() (
  started="$(list started | grep ^)"
  up="$(list up | grep ^)"
  if [ -z "${started}" ] && [ -z "${up}" ]; then
    echo Compressing
    echo
    cd ~/Library/Containers/com.utmapp.UTM/Data/Documents \
      && (
        du -sch "*utm"
        for i in */*/*qcow2; do
          qemu-img convert -O qcow2 "${i}" shrunk && mv shrunk "${i}"
        done
        echo
        du -sch "*utm"
      )
  else
    echo Can\'t compress, some machines are still running:
    (
      echo "${started}"
      echo "${up}"
    ) | sort | uniq
  fi
)

backup() (
  started="$(list started | grep ^)"
  up="$(list up | grep ^)"
  if [ -z "${started}" ] && [ -z "${up}" ]; then
    echo Backing up
    cd "/Volumes/VaultBackup/snapshots/daily.0/UTM VMs" \
      && rsync -Pavessh --delete --exclude UTM?storage?dir ~/Library/Containers/com.utmapp.UTM/Data/Documents/ .
  else
    echo Can\'t backup, some machines are still running:
    (
      echo "${started}"
      echo "${up}"
    ) | sort | uniq
  fi
)

bounce() (
  MACHINE="$1"
  shift
  if [ "${MACHINE}" = "all" ]; then
    for candidate in $(list up); do
      bounce "${candidate}"
    done
  elif [ -z "${MACHINE}" ]; then # no args? error
    echo utm bounce all\|\{list of machines\}
  elif [ -n "$1" ]; then # multi? iterate
    for candidate in "${MACHINE}" "$@"; do
      bounce "${candidate}"
    done
  elif [[ "${MACHINE}" == *\** ]]; then # wildcard? match and iterate
    for candidate in $(list up); do
      if [ "${candidate}" = "${MACHINE}" ]; then
        bounce "${candidate}"
      fi
    done
  else
    if grep ^"${MACHINE}"\$ <(list up) >/dev/null 2>/dev/null; then
      stop "${MACHINE}"
      while grep "^${MACHINE}$" <(list started) >/dev/null 2>&1; do
        sleep 5
        echo ... waiting
      done
      sleep 5
      start "${MACHINE}"
    else
      echo What\'s "${MACHINE}"?
    fi
  fi
)

stop() (
  MACHINE="$1"
  shift
  if [ "${MACHINE}" = "all" ]; then
    for candidate in $(list up); do
      stop "${candidate}"
    done
  elif [ -z "${MACHINE}" ]; then
    echo utm stop all\|\{list of machines\}
  elif [ -n "$1" ]; then
    for candidate in "${MACHINE}" "$@"; do
      stop "${candidate}"
    done
  elif [[ "${MACHINE}" == *\** ]]; then
    for candidate in $(list up); do
      if [ "${candidate}" = "${MACHINE}" ]; then
        stop "${candidate}"
      fi
    done
  else
    if grep ^"${MACHINE}"\$ <(list up) >/dev/null 2>/dev/null; then
      echo stopping "${MACHINE}"
      utmctl stop "${MACHINE}" --request >/dev/null 2>/dev/null
      sleep 5
    else
      echo What\'s "${MACHINE}"?
    fi
  fi
)

start() (
  MACHINE="$1"
  shift
  if [ "${MACHINE}" = "all" ]; then
    for candidate in $(list stopped); do
      start "${candidate}"
    done
  elif [ -z "${MACHINE}" ]; then
    echo utm start all\|\{list of machines\}
  elif [ -n "$1" ]; then # multi? iterate
    for candidate in "${MACHINE}" "$@"; do
      start "${candidate}"
    done
  elif [[ "${MACHINE}" == *\** ]]; then
    # elif echo "${MACHINE}" | grep -q "^*\**"; then
    for candidate in $(list stopped); do
      if [ "${candidate}" = "${MACHINE}" ]; then
        start "${candidate}"
      fi
    done
  else
    if grep ^"${MACHINE}"\$ <(list stopped) >/dev/null 2>/dev/null; then
      echo starting "${MACHINE}"
      utmctl start "${MACHINE}" >/dev/null 2>/dev/null
      ALTERNATE_NAME="$(echo "${MACHINE}" | sed 's/.local$//')"
      while ! (ping -c1 "${MACHINE}" || ping -c1 "${ALTERNATE_NAME}") >/dev/null 2>&1; do
        echo ... waiting
        sleep 5
      done
    else
      echo What\'s "${MACHINE}"?
    fi
  fi
)

status() (
  MACHINE="$1"
  shift
  if [ "${MACHINE}" = "all" ]; then
    for status in stopped started up; do
      STATUSES="$(list "${status}")"
      if [ -n "${STATUSES}" ]; then
        echo "${status}"
        echo "${STATUSES}" | sed 's/ /\n/g' | sed 's/^/  /'
      fi
    done
  elif [ -z "$1" ]; then
    echo utm status all\|\{list of machines\}
  elif [ -n "$1" ]; then
    echo status \$machine not yet implemented, sorry
  elif [[ "${MACHINE}" == *\** ]]; then
    # elif echo "${MACHINE}" | grep -q "^*\**"; then
    echo status \$wildcard not yet implemented, sorry
  fi
)

list_complete() (
  utmctl list | grep -v UUID
)

listall() (
  list_complete | awk '{print $3}'
)

liststarted() (
  list_complete | awk '$2 ~ /started/ { print $3; next }'
)

listup() (
  for candidate in $(liststarted); do
    ALTERNATE_NAME="$(echo "${candidate}" | sed 's/.local$//')"
    (ping -c1 "${candidate}" || ping -c1 "${ALTERNATE_NAME}") >/dev/null 2>&1 && echo "${candidate}"
  done
)

list() (
  TYPE="$1"
  shift
  if [ "${TYPE}" = "started" ]; then
    liststarted
  elif [ "${TYPE}" = "all" ]; then
    listall
  elif [ "${TYPE}" = "up" ]; then
    listup
  elif [ "${TYPE}" = "stopped" ]; then
    grep -v -f <(liststarted) <(listall)
  else
    echo utm list all\|started\|up\|stopped
  fi
)

main "$@"
