#!/usr/bin/env bash
# crosscode: installs, updates and moves church installs on this server (ROADMAP-v3 §8,
# docs/EVENTS-2.2-PLAN.md §4). `crosscode help` lists the commands.
#
# On a server this is a checkout of crosscode-platform's main in /opt/crosscode/tools, linked as
# /usr/local/bin/crosscode. Every run first updates that checkout (git pull --ff-only), then runs
# from a copy, so a checkout never changes the script while it runs.
#
# Environment: CROSSCODE_SITES (default /var/www/sites), CROSSCODE_REPO (the monorepo's git URL),
# CROSSCODE_TOOLS_DIR (default /opt/crosscode/tools), CROSSCODE_NO_UPDATE=1 (skip the update).
set -Eeuo pipefail

CROSSCODE_TOOLS_DIR="${CROSSCODE_TOOLS_DIR:-/opt/crosscode/tools}"

if [ -z "${CROSSCODE_HOME:-}" ]; then
  src="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)"
  root="$(cd "$src/.." && pwd)"
  if [ "${CROSSCODE_NO_UPDATE:-}" != 1 ] && [ "$root" = "$CROSSCODE_TOOLS_DIR" ] && [ -d "$root/.git" ]; then
    git -C "$root" pull --ff-only --quiet ||
      printf '!!> Couldn'"'"'t update %s; running the version that is there.\n' "$root" >&2
  fi
  copy="$(mktemp -d /tmp/crosscode.XXXXXX)"
  cp -R "$src/." "$copy/"
  CROSSCODE_HOME="$copy" CROSSCODE_FROM="$root" exec bash "$copy/crosscode" "$@"
fi

# Options for every command, taken out of the arguments here: --json (a crosscode.script-report/1
# on stdout at the end, the log on stderr) and --config <file> (the .env values by layer, from
# the agent).
CROSSCODE_JSON=0
CROSSCODE_CONFIG="${CROSSCODE_CONFIG:-}"
args=()
while [ $# -gt 0 ]; do
  case "$1" in
    --json) CROSSCODE_JSON=1; shift ;;
    --config)
      [ $# -ge 2 ] || { echo '!!> --config needs a file.' >&2; exit 1; }
      CROSSCODE_CONFIG="$2"; shift 2 ;;
    *) args+=("$1"); shift ;;
  esac
done
set -- "${args[@]+"${args[@]}"}"
export CROSSCODE_CONFIG

# shellcheck source=lib/common.sh
source "$CROSSCODE_HOME/lib/common.sh"
# shellcheck source=lib/env.sh
source "$CROSSCODE_HOME/lib/env.sh"
# shellcheck source=lib/frpc.sh
source "$CROSSCODE_HOME/lib/frpc.sh"
# shellcheck source=lib/deploy.sh
source "$CROSSCODE_HOME/lib/deploy.sh"
# shellcheck source=lib/status.sh
source "$CROSSCODE_HOME/lib/status.sh"
# shellcheck source=lib/install.sh
source "$CROSSCODE_HOME/lib/install.sh"
# shellcheck source=lib/adopt.sh
source "$CROSSCODE_HOME/lib/adopt.sh"
# shellcheck source=lib/manage.sh
source "$CROSSCODE_HOME/lib/manage.sh"

# At the end: the report (with --json), and the copy this runs from is removed (only ever a
# mktemp folder, never a checkout).
on_exit() {
  local rc=$?
  [ "$CROSSCODE_JSON" != 1 ] || report_emit "$rc"
  if [[ "$CROSSCODE_HOME" == /tmp/crosscode.* ]]; then rm -rf "$CROSSCODE_HOME"; fi
  return "$rc"
}
trap on_exit EXIT

command="${1:-help}"
[ $# -gt 0 ] && shift
if [ "$CROSSCODE_JSON" = 1 ]; then
  # The report goes to the real stdout (fd 3); everything else to stderr.
  exec 3>&1 1>&2
  report_init "$command"
fi

if [ -n "$CROSSCODE_CONFIG" ]; then
  [ -f "$CROSSCODE_CONFIG" ] || die "--config: there's no file $CROSSCODE_CONFIG."
  node -e 'JSON.parse(require("fs").readFileSync(process.argv[1], "utf8"))' "$CROSSCODE_CONFIG" 2>/dev/null ||
    die "--config: $CROSSCODE_CONFIG isn't JSON."
fi

usage() {
  cat <<EOF
crosscode: Cross Code installs on this server ($(git -C "${CROSSCODE_FROM:-.}" rev-parse --short HEAD 2>/dev/null || echo 'unknown version'))

  crosscode deploy <church> [events] [website] [app]   update Accounts and the products named
  crosscode deploy --every-church [events] …           the same, for every church here
  crosscode deploy <church> … --check                  only the checks; changes nothing
  crosscode status [<church>]                          versions, latest releases, health
  crosscode install <church> --products events --domain <address>   a new church
  crosscode adopt <church> --events-dir <old folder>   move an existing Cross Events install here
  crosscode adopt <church> --undo                      go back to the old folder (within 14 days)
  crosscode restart <church> [events]                  reload the PM2 processes
  crosscode export <church> --out <file.zip>           the church's data and uploads
  crosscode uninstall <church> --confirm <church>      remove it (a final backup is kept 30 days)
  crosscode purge <church> --confirm <church>          delete what uninstall kept
  crosscode help [<command>]                           this, or a command's options

Every command takes --json (a report at the end) and --config <file> (settings from the Hub).
Churches live in $CROSSCODE_SITES/<church>/ (church.env, one checkout per product).
EOF
}

case "$command" in
  deploy) cmd_deploy "$@" ;;
  status) cmd_status "$@" ;;
  install) cmd_install "$@" ;;
  adopt) cmd_adopt "$@" ;;
  restart) cmd_restart "$@" ;;
  export) cmd_export "$@" ;;
  uninstall) cmd_uninstall "$@" ;;
  purge) cmd_purge "$@" ;;
  add) die "\`crosscode add\` comes with the second product (phase 3)." ;;
  help|-h|--help)
    case "${1:-}" in
      deploy) deploy_usage ;;
      status) status_usage ;;
      install) install_usage ;;
      adopt) adopt_usage ;;
      restart|export|uninstall|purge) manage_usage ;;
      *) usage ;;
    esac ;;
  *) usage; die "Unknown command \"$command\"." ;;
esac
