#!/bin/sh
# Installs the trdrs back office and starts it:
#
#   curl -fsSL https://trdrs.co/install/backoffice.sh | sh
#
# It downloads the release this script was published with, checks it against its published checksum,
# writes an environment file with no secret in it and starts the server on http://127.0.0.1:8787. It
# asks nothing. When the server starts it opens the trdrs page that approves this back office; once
# the owner approves, it opens the back office itself, connected, to choose a sign-in password and
# pick or create the venue.
#
# TRDRS_BACKOFFICE_DIR, PORT, TRDRS_ENVIRONMENT, TRDRS_API_URL and TRDRS_APP_ORIGIN may be set in the
# environment, TRDRS_NO_START=1 installs without starting and TRDRS_NO_BROWSER=1 prints the addresses
# without opening a browser. Production needs TRDRS_ENVIRONMENT=production and an explicit TRDRS_API_URL.
#
# Running it again in the same place installs the newer release beside the old one and keeps the
# existing environment file and data directory, so an update is the same command. The whole script
# sits in one function called on its last line, so a download cut short runs nothing.

main() {
  set -eu
  version='0.3.29'
  # The web image rewrites this to the host that served the script, so the sandbox copy downloads the
  # sandbox release and the production copy the production one.
  downloads="${TRDRS_DOWNLOAD_URL:-https://trdrs.co/downloads}"
  environment="${TRDRS_ENVIRONMENT:-sandbox}"
  dir="${TRDRS_BACKOFFICE_DIR:-trdrs-backoffice}"
  port="${PORT:-8787}"

  case "$environment" in
    sandbox) api="${TRDRS_API_URL:-https://sandbox.trdrs.co}"; app_origin="${TRDRS_APP_ORIGIN:-https://sandbox.trdrs.co}" ;;
    production)
      [ -n "${TRDRS_API_URL:-}" ] || fail "Production needs TRDRS_API_URL set to the production API origin."
      api="$TRDRS_API_URL"; app_origin="${TRDRS_APP_ORIGIN:-https://app.trdrs.co}" ;;
    *) fail "TRDRS_ENVIRONMENT must be sandbox or production." ;;
  esac

  need curl; need tar; need node
  node_major="$(node -p 'process.versions.node.split(".")[0]')"
  [ "$node_major" -ge 22 ] || fail "The back office needs Node.js 22 or newer; this machine has $(node -v)."
  if command -v shasum >/dev/null 2>&1; then sha_check='shasum -a 256 -c'
  elif command -v sha256sum >/dev/null 2>&1; then sha_check='sha256sum -c'
  else fail "Neither shasum nor sha256sum is installed, so the download cannot be checked."; fi

  say "Installing trdrs back office $version ($environment) into ./$dir"
  mkdir -p "$dir"
  cd "$dir"
  release="trdrs-backoffice-$version"
  if [ -d "$release" ]; then
    say "Release $version is already unpacked here; keeping it."
  else
    scratch="$(mktemp -d)"
    curl -fsSL "$downloads/$release.tgz" -o "$scratch/$release.tgz" || fail "Could not download $downloads/$release.tgz"
    curl -fsSL "$downloads/$release.tgz.sha256" -o "$scratch/$release.tgz.sha256" || fail "Could not download the checksum."
    (cd "$scratch" && $sha_check "$release.tgz.sha256" >/dev/null) || fail "The download does not match its published checksum. Nothing was installed."
    tar -xzf "$scratch/$release.tgz"
    rm -rf "$scratch"
    say "Downloaded and verified $release.tgz"
  fi

  # The data directory sits beside the releases, so an update keeps the selected venue.
  # Only this user may read the installation's settings.
  data_dir="$(pwd -P)/data"
  (umask 077 && mkdir -p "$data_dir")

  if [ -f .env ]; then
    say "Keeping the existing .env."
  else
    (umask 077 && cat > .env <<EOF
TRDRS_ENVIRONMENT=$environment
TRDRS_API_URL=$api
TRDRS_APP_ORIGIN=$app_origin
HOST=127.0.0.1
PORT=$port
TRDRS_DATA_DIR="$data_dir"
TRDRS_SECURE_COOKIE=false
TRDRS_SESSION_HOURS=12
EOF
)
    say "Wrote .env. Venue selection is kept in $data_dir, readable only by you."
  fi

  # `current` names the release the launcher runs. An update made from inside the back office points
  # it at the release it installs and restarts into that one; running this script points it here.
  printf '%s\n' "$release" > current
  cat > start.sh <<'EOF'
#!/bin/sh
# Starts the launcher of the release `current` names, which runs that release with ../.env and
# restarts into the release an update installs.
cd "$(dirname "$0")" && exec node "$(cat current)/server/run.mjs"
EOF
  chmod +x start.sh

  say ""
  say "Start it again any time with: ./$dir/start.sh"
  say "When it starts, it opens trdrs in your browser to approve this back office, then opens the"
  say "back office. The addresses are printed below too."
  if [ "${TRDRS_NO_START:-}" = 1 ]; then return 0; fi
  say "Press Ctrl-C to stop."
  say ""
  exec ./start.sh
}

say() { printf '%s\n' "$*" >&2; }
fail() { printf 'trdrs back office: %s\n' "$*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || fail "$1 is required but not installed."; }

main "$@"
