#!/bin/sh
# Installs demetra-cli's bundled single-file release. Uploaded to the CLI
# CDN's bucket root by demetra-cli-release.yml, served at
# https://cli.<zone>/install.sh — and at the bare https://cli.<zone> too,
# via the CloudFront 403->install.sh rewrite (cli_cdn.py).
set -eu

CDN_HOST="${DEMETRA_CLI_CDN_HOST:-cli.demetra.simetrik.com}"
INSTALL_DIR="${DEMETRA_CLI_INSTALL_DIR:-$HOME/.demetra/bin}"

if ! command -v node >/dev/null 2>&1; then
  echo "demetra-cli needs Node.js >= 20 on PATH. Install it first (e.g. https://nodejs.org), then re-run this script." >&2
  exit 1
fi

NODE_MAJOR=$(node -e 'console.log(process.versions.node.split(".")[0])')
if [ "$NODE_MAJOR" -lt 20 ]; then
  echo "demetra-cli needs Node.js >= 20, found $(node -v). Upgrade Node, then re-run this script." >&2
  exit 1
fi

TMP_DIR=$(mktemp -d)
trap 'rm -rf "$TMP_DIR"' EXIT

echo "Downloading demetra-cli (stable) from https://$CDN_HOST ..."
# `demetra` and `demetra.sha256` — the exact names demetra-cli-release.yml
# uploads (it renames the esbuild bundle before publishing), not the raw
# `demetra-bundled.mjs` build artifact name.
curl -fsSL "https://$CDN_HOST/cli/stable/demetra" -o "$TMP_DIR/demetra"
curl -fsSL "https://$CDN_HOST/cli/stable/demetra.sha256" -o "$TMP_DIR/demetra.sha256"

cd "$TMP_DIR"
if command -v sha256sum >/dev/null 2>&1; then
  sha256sum -c demetra.sha256
elif command -v shasum >/dev/null 2>&1; then
  shasum -a 256 -c demetra.sha256
else
  echo "no sha256sum or shasum found — cannot verify the download's integrity, refusing to install an unverified binary" >&2
  exit 1
fi

mkdir -p "$INSTALL_DIR"
# SOUP-1138: the CLI is an ES module WITHOUT an extension, so it starts only
# because Node detects it as one — and a package.json above it saying
# "type": "commonjs" switches that detection off (measured 2026-09-23: every
# version dies there with "Cannot use import statement outside a module"). The
# NEAREST package.json wins, so one beside the binary makes the install
# independent of whatever is above it. Written only when absent: one that is
# already there is somebody else's, and is left alone. And only in a folder
# that is OURS: in a shared one (~/.local/bin) a "type": "module" changes how
# Node loads every other extensionless script there — measured, a CommonJS CLI
# beside it dies with "require is not defined in ES module scope".
PROPIA=1
for f in "$INSTALL_DIR"/*; do
  [ -e "$f" ] || continue
  case "$(basename "$f")" in
    demetra|demetra.origin|demetra.sha256|package.json) ;;
    *) PROPIA=0 ;;
  esac
done
if [ ! -e "$INSTALL_DIR/package.json" ] && [ "$PROPIA" = 1 ]; then
  printf '{ "type": "module" }\n' > "$INSTALL_DIR/package.json"
fi
# And the new binary must START before it replaces anything. It is tried from
# beside the target — same folder, same nearest package.json — and only then
# moved over it, so a binary that does not start never takes the place of one
# that does. Inside a temp FOLDER and named `demetra`: a name like
# `.demetra-install.123` has an "extension" (`.123`) that Node refuses under
# "type": "module" (ERR_UNKNOWN_FILE_EXTENSION) — the check would fail for a
# binary that is fine.
NEWDIR=$(mktemp -d "$INSTALL_DIR/.demetra-install-XXXXXX")
NEW="$NEWDIR/demetra"
cp demetra "$NEW"
chmod +x "$NEW"
if ! "$NEW" --version 2>/dev/null | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+'; then
  rm -rf "$NEWDIR"
  echo "refusing to install: the downloaded demetra does not start here (\`--version\` gave no version) — $INSTALL_DIR/demetra is untouched." >&2
  if [ "$PROPIA" = 0 ] && [ ! -e "$INSTALL_DIR/package.json" ]; then
    echo "  $INSTALL_DIR holds other files, so this installer did not write a package.json there (it would change how Node loads them)." >&2
    echo "  This CLI is an ES module and does not start under the \"type\": \"commonjs\" above it — install it in a folder of its own (DEMETRA_CLI_INSTALL_DIR)." >&2
  fi
  if [ -e "$INSTALL_DIR/package.json" ] && ! grep -q '"module"' "$INSTALL_DIR/package.json"; then
    echo "  $INSTALL_DIR/package.json is not \"type\": \"module\", and this CLI is an ES module: it only starts under \"module\"." >&2
    echo "  That file was not written by this installer, so it was left alone — install into a folder of its own (DEMETRA_CLI_INSTALL_DIR), or change that file." >&2
  fi
  exit 1
fi
mv "$NEW" "$INSTALL_DIR/demetra"
rmdir "$NEWDIR"
# SOUP-1000: record WHERE this binary came from, beside the binary — the CLI
# shows it next to the active environment (`demetra version --verbose`), so a
# dev-binary/prod-API combination is one visible line instead of a deduction.
printf '%s\n' "$CDN_HOST" > "$INSTALL_DIR/demetra.origin"

echo "Installed demetra to $INSTALL_DIR/demetra"

# "I installed it" and "my shell runs it" are different facts, and only the
# second one is the feature. Measured on a real machine on 2026-09-13: the
# correct 24-verb binary had been sitting in $INSTALL_DIR since the day before
# while `demetra` still resolved to a ten-day-old `npm -g` with 8 verbs — this
# script printed "Installed demetra to …" and changed nothing an operator could
# observe. Saying WHICH one wins turns a silent no-op into one visible line.
WINNER="$(command -v demetra 2>/dev/null || true)"

case ":$PATH:" in
  *":$INSTALL_DIR:"*)
    if [ -n "$WINNER" ] && [ "$WINNER" != "$INSTALL_DIR/demetra" ]; then
      echo
      echo "WARNING: another 'demetra' comes FIRST on your PATH, so typing"
      echo "'demetra' still runs that one, not the version just installed:"
      echo "  $WINNER"
      echo "Put this one ahead of it, or remove the other:"
      echo "  export PATH=\"$INSTALL_DIR:\$PATH\""
    else
      echo "Run: demetra login"
    fi
    ;;
  *)
    echo "Add $INSTALL_DIR to your PATH, e.g.:"
    echo "  echo 'export PATH=\"$INSTALL_DIR:\$PATH\"' >> ~/.bashrc   # or ~/.zshrc"
    if [ -n "$WINNER" ]; then
      echo "Prepend it, do NOT append: another 'demetra' already answers first:"
      echo "  $WINNER"
    fi
    echo "Then run: demetra login"
    ;;
esac

# A shell ALIAS beats PATH outright and is invisible from here — this script is
# not the interactive shell, so `command -v` cannot see one. On the machine
# above, `alias demetra=...tmux-launch.sh` in ~/.zshrc won over both binaries.
echo
echo "Check what your shell will actually run:"
echo "  type demetra                       # an alias wins over PATH"
echo "  demetra ship --help | head -1      # must say: Usage: demetra ship [options]"
