#!/usr/bin/env bash
set -euo pipefail

# Appmint hub agent — one-command installer.
#
#   curl -sSL https://web.appmint.space/hub-agent/install | sudo bash
#
# That is the whole thing. This script works out which platform it is on and
# fetches the right installer, so a client only ever has to be given one URL.
#
# Windows cannot pipe to bash; use PowerShell as Administrator instead:
#   irm https://web.appmint.space/hub-agent/install.ps1 | iex
#
# Pinned at publish time, same as every other installer here — the version and
# base URL below are rewritten by deploy.mjs, so this bootstrap and the
# installer it pulls always come from the same release.

HUB_VERSION="${HUB_VERSION:-dev}"
RELEASE_BASE_URL="${RELEASE_BASE_URL:-__RELEASE_BASE_URL__}"

if [ "${RELEASE_BASE_URL}" = "__RELEASE_BASE_URL__" ]; then
  echo "install: this bootstrap was not published (no release URL baked in)." >&2
  echo "         Run scripts/install.sh or scripts/install-mac.sh from a clone." >&2
  exit 1
fi

if [ "$(id -u)" -ne 0 ]; then
  echo "install: must run as root — pipe it to 'sudo bash', not 'bash'." >&2
  echo "         curl -sSL ${RELEASE_BASE_URL}/install | sudo bash" >&2
  exit 1
fi

case "$(uname -s)" in
  Linux)  installer="install.sh" ;;
  Darwin) installer="install-mac.sh" ;;
  *)
    echo "install: unsupported platform '$(uname -s)'." >&2
    echo "         On Windows, run this in PowerShell as Administrator:" >&2
    echo "           irm ${RELEASE_BASE_URL}/install.ps1 | iex" >&2
    exit 1
    ;;
esac

echo "install: $(uname -s) detected — fetching ${installer} (v${HUB_VERSION})"

tmp="$(mktemp -d)"
trap 'rm -rf "${tmp}"' EXIT
curl -fsSL "${RELEASE_BASE_URL}/${installer}" -o "${tmp}/${installer}"
chmod +x "${tmp}/${installer}"

# The platform installer downloads and checksums the tarball itself; it just
# needs to know which release it belongs to. Exported rather than passed as
# args so it survives however the child script re-invokes things.
export HUB_VERSION RELEASE_BASE_URL
exec bash "${tmp}/${installer}"
