#!/bin/bash
#
# Purpose : Tools for working on CoreDesktop itself (see README.md)

SELF="$(readlink -f "${BASH_SOURCE[0]}")"
LIB="$(dirname "$SELF")/../lib"

source "$LIB/common.sh"

usage() {
  cat << EOF
Usage: coredesktop-dev <command> [--help]

  doctor      Check this machine is set up to work on CoreDesktop
  check       Run the linters and tests on the working copy
  try         Run the working copy's code as if it were installed, in a throwaway home
  deployed    Show, or restore, the installed copy of CoreDesktop
  hooks       Install or remove the pre-push hook that runs check
  smoketest   Test install and update on a virtual machine
EOF
}

command="${1:-}"
shift

case "$command" in
  doctor | check | try | deployed | hooks | smoketest) ;;
  "" | -h | --help | help)
    usage
    exit 0
    ;;
  *)
    usage >&2
    exit 1
    ;;
esac

# In a Flatpak (an editor's terminal, say), pacman, systemctl, qemu and the
# host's tools aren't there: run on the host instead
if in_flatpak && [[ "${1:-}" != -h && "${1:-}" != --help ]]; then
  echo "Running in a Flatpak; running coredesktop-dev $command on the host (flatpak-spawn --host)." >&2
  exec flatpak-spawn --host --env=COREDESKTOP_DEV_VIA_FLATPAK=1 "$SELF" "$command" "$@"
fi

source "$LIB/$command.sh"
"cmd_$command" "$@"
