#!/bin/sh
# NomosX installer - served from https://nomosx.io/install.sh
#
#   curl -fsSL https://nomosx.io/install.sh | sh                 (detect + choose)
#   curl -fsSL https://nomosx.io/install.sh | sh -s -- claude    (one surface)
#   curl -fsSL https://nomosx.io/install.sh | sh -s -- --all --yes
#   curl -fsSL https://nomosx.io/install.sh | sh -s -- --help    (every flag)
#
# A LAUNCHER for the native NomosX installer (the nomosx package, which is not
# offered through npm). It proves that program is the release's, runs it, and does nothing else:
#
#   1. downloads latest.json and latest.json.sig and verifies the ed25519
#      signature over the exact bytes against RELEASE_PUBKEY below. An unsigned
#      pointer, a bad signature, and a signed pointer from an older release
#      line (no signed `releases` map) are all refused.
#   2. downloads the installer package (nomosx-npm.tgz) and requires its
#      sha256 to equal the npm.sha256 that signed latest.json lists.
#   3. extracts its one file (package/build/nomosx.mjs) and runs
#      `node nomosx.mjs install <your arguments>` in place of this script.
#
# The installer then does the install: it verifies latest.json again for
# itself, checks the release tarball's checksum and sealed integrity manifest,
# swaps it into ~/.nomosx/dist and wires the surfaces. Flags, output and exit
# codes are the installer's own. RE-RUNNING THIS IS THE UPDATE.
#
# --check, --help and --from <tarball> are answered by the installer already on
# this machine when its sealed manifest verifies (a query, or a staged update
# applied without the network), and by a downloaded one otherwise.
#
# Needs curl, tar and node. Never reads stdin: under `curl | sh` stdin IS this
# script, and the installer runs with stdin closed (it asks on /dev/tty).
# NOMOSX_DOWNLOAD_BASE points it at another site; NOMOSX_ALLOW_UNSIGNED=1
# accepts an unsigned latest.json there (development and test sites only).
#
# Terms: https://nomosx.io/terms · Privacy: https://nomosx.io/privacy
# License: PolyForm Shield 1.0.0. Uninstall: curl -fsSL https://nomosx.io/uninstall.sh | sh

set -eu

BASE="${NOMOSX_DOWNLOAD_BASE:-https://nomosx.io/dist}"
NH="${NOMOSX_HOME:-$HOME/.nomosx}"
COMMAND="install"

# The NomosX release signing key, PUBLIC half: base64 of the SPKI DER encoding
# of the ed25519 public key. THIS LITERAL MUST STAY BYTE-IDENTICAL TO PUBLIC_KEY
# IN claude-code/scripts/release-key.mjs (scripts/validate.mjs enforces it).
RELEASE_PUBKEY="MCowBQYDK2VwAyEArEYfAP87P31ffVwf0gB/LsoWYnJ3QwiMaqqDnClqOwo="

# ---- the verifier (node builtins only; identical in install.sh and uninstall.sh) ----
#   pointer <dir> <base> <key> <command>    latest.json(.sig) in <dir> -> "<version> <npm sha256>", or "ALIAS"
#   package <dir> <sha256|-> - <command>    nomosx-npm.tgz in <dir> matches the signed digest (- = its .sha256)
#   local <tree>                <tree> carries installer/nomosx.mjs, listed in a manifest that verifies
VERIFY='
const fs = require("fs"), crypto = require("crypto"), path = require("path"), cp = require("child_process");
const argv = process.argv.slice(1), first = argv.findIndex((x) => x === "pointer" || x === "package" || x === "local");
const [mode, a, b, c, command] = argv.slice(first < 0 ? 0 : first); // `node -e` (sh) or `node verify.cjs` (PowerShell)
const allow = process.env.NOMOSX_ALLOW_UNSIGNED === "1";
const die = (m) => { process.stderr.write(`[nomosx] ERROR: ${command === "uninstall" ? `no verified uninstaller could be downloaded: ${m.split(" - refusing")[0]} (nothing changed)` : m}\n`); process.exit(1); };
const read = (f) => { try { return fs.readFileSync(f); } catch { return null; } };
const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex");
const HEX = /^[0-9a-f]{64}$/;
if (mode === "pointer") {
  const [dir, base, key] = [a, b, c];
  const bytes = read(path.join(dir, "latest.json"));
  let j = null;
  try { j = bytes ? JSON.parse(bytes.toString("utf8")) : null; } catch { j = null; }
  const version = j && typeof j.version === "string" ? j.version : "";
  const alias = (why) => {
    process.stderr.write(`[nomosx] WARNING: NOMOSX_ALLOW_UNSIGNED=1 and ${why} - running the installer package at ${base}/nomosx-npm.tgz, checked only against its .sha256\n`);
    process.stdout.write("ALIAS\n");
    process.exit(0);
  };
  if (!version) {
    if (allow) alias("latest.json is not reachable");
    die(`latest.json is not reachable at ${base} (or is not a release pointer) - refusing to install a release nothing verified (nothing was downloaded, nothing changed)`);
  }
  const sig = read(path.join(dir, "latest.json.sig"));
  let state = "unsigned";
  if (sig) {
    try {
      const pub = crypto.createPublicKey({ key: Buffer.from(key, "base64"), format: "der", type: "spki" });
      state = crypto.verify(null, bytes, pub, Buffer.from(sig.toString("utf8").trim(), "base64")) ? "verified" : "invalid";
    } catch { state = "invalid"; }
  }
  if (state === "invalid") die(`latest.json at ${base} is signed with a key this installer does not trust - refusing to go any further (nothing was downloaded, nothing changed)`);
  if (state === "unsigned" && !allow) die(`latest.json at ${base} is UNSIGNED - refusing to install a release no signature covers (nothing was downloaded, nothing changed)`);
  if (!/^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$/.test(version)) die(`latest.json carries an unusable version (${JSON.stringify(version)}) - refusing to build a URL or a path from it (nothing was downloaded, nothing changed)`);
  const releases = j.releases, own = j.tarball && j.tarball.sha256;
  const hardened = /^[0-9]+$/.test(String(j.seq ?? "")) && Number.isSafeInteger(Number(j.seq)) && releases && typeof releases === "object" && !Array.isArray(releases) && Object.hasOwn(releases, version) && typeof own === "string" && HEX.test(own) && releases[version] === own;
  if (state === "verified" && !hardened && !allow) die(`latest.json at ${base} predates signed release digests (no releases map, or one that does not list ${version}) - refusing a pointer this installer cannot hold to its trust policy (nothing was downloaded, nothing changed)`);
  const npm = j.npm && j.npm.sha256;
  if (typeof npm !== "string" || !HEX.test(npm)) {
    if (allow && state !== "verified") alias("latest.json lists no installer package");
    die(`the release at ${base} lists no native installer (latest.json has no npm.sha256) - nothing was downloaded, nothing changed`);
  }
  process.stdout.write(`${version} ${npm}\n`);
} else if (mode === "package") {
  const [dir, expected] = [a, b];
  const body = read(path.join(dir, "nomosx-npm.tgz"));
  if (!body) die("the installer package could not be read - refusing to run it (nothing changed)");
  if (expected === "-") {
    const side = read(path.join(dir, "nomosx-npm.tgz.sha256"));
    if (!side || side.toString("utf8").split("\n")[0].split(" ")[0] !== sha256(body)) die("the installer package does not match its .sha256 - refusing to run it (nothing changed)");
  } else if (sha256(body) !== expected) {
    die("the installer package does not match the sha256 in the signed latest.json - refusing to run it (nothing changed)");
  }
} else if (mode === "local") {
  const tree = a;
  let files = null;
  try { files = JSON.parse(fs.readFileSync(path.join(tree, "integrity.json"), "utf8")).files; } catch { files = null; }
  if (!files || typeof files !== "object" || !Object.hasOwn(files, "installer/nomosx.mjs")) process.exit(1);
  const checker = path.join(tree, "claude-code", "scripts", "integrity.mjs");
  const r = cp.spawnSync(process.execPath, [checker, "--verify", tree], { stdio: "ignore", timeout: 60000 });
  process.exit(r.status === 0 ? 0 : 1);
} else {
  die(`unknown verifier mode ${mode}`);
}
'

fail() { printf '[nomosx] ERROR: %s\n' "$*" >&2; exit 1; }

main() {
  command -v node >/dev/null 2>&1 || fail "node (>=20) is required - install Node.js from https://nodejs.org, then re-run"
  command -v tar >/dev/null 2>&1 || fail "tar is required"

  # A query, or a staged update applied offline: the installer on this machine.
  local_ok=""
  for arg in "$@"; do
    case "$arg" in --check|--help|-h|--from) local_ok=1 ;; esac
  done
  if [ -n "$local_ok" ]; then
    self_dir=""
    case "$0" in */install.sh) if [ -f "$0" ]; then self_dir=$(cd "$(dirname "$0")" && pwd); fi ;; esac
    for tree in "$self_dir" "$NH/dist"; do
      if [ -n "$tree" ] && [ -f "$tree/installer/nomosx.mjs" ] && node -e "$VERIFY" local "$tree"; then
        exec node "$tree/installer/nomosx.mjs" "$COMMAND" "$@" </dev/null
      fi
    done
  fi

  command -v curl >/dev/null 2>&1 || fail "curl is required"
  WORK=$(mktemp -d "${TMPDIR:-/tmp}/nomosx-launch.XXXXXX") || fail "cannot create a temporary directory"
  trap 'rm -rf "$WORK"' EXIT
  trap 'exit 129' HUP
  trap 'exit 130' INT
  trap 'exit 143' TERM

  curl -fsSL --max-time 30 -o "$WORK/latest.json" "$BASE/latest.json" 2>/dev/null || rm -f "$WORK/latest.json"
  curl -fsSL --max-time 30 -o "$WORK/latest.json.sig" "$BASE/latest.json.sig" 2>/dev/null || rm -f "$WORK/latest.json.sig"
  pointer=$(node -e "$VERIFY" pointer "$WORK" "$BASE" "${NOMOSX_RELEASE_PUBKEY:-$RELEASE_PUBKEY}" "$COMMAND") || exit 1

  if [ "$pointer" = "ALIAS" ]; then
    curl -fsSL --max-time 120 -o "$WORK/nomosx-npm.tgz" "$BASE/nomosx-npm.tgz" 2>/dev/null || fail "the installer package is not reachable at $BASE/nomosx-npm.tgz"
    curl -fsSL --max-time 30 -o "$WORK/nomosx-npm.tgz.sha256" "$BASE/nomosx-npm.tgz.sha256" 2>/dev/null || fail "the installer package has no .sha256 at $BASE"
    node -e "$VERIFY" package "$WORK" - - "$COMMAND" || exit 1
  else
    version=${pointer%% *}
    digest=${pointer#* }
    # The versioned package first; the alias carries the same bytes once a
    # release is live, and both are held to the same signed digest.
    curl -fsSL --max-time 120 -o "$WORK/nomosx-npm.tgz" "$BASE/v/$version/nomosx-npm.tgz" 2>/dev/null \
      || curl -fsSL --max-time 120 -o "$WORK/nomosx-npm.tgz" "$BASE/nomosx-npm.tgz" 2>/dev/null \
      || fail "the installer package is not reachable at $BASE (nothing changed)"
    node -e "$VERIFY" package "$WORK" "$digest" - "$COMMAND" || exit 1
  fi

  tar -xzf "$WORK/nomosx-npm.tgz" -C "$WORK" package/build/nomosx.mjs 2>/dev/null || fail "the installer package could not be unpacked (nothing changed)"
  # From here the installer owns the temporary directory: it removes it as soon
  # as it has loaded (it is one file, already in memory).
  trap - EXIT HUP INT TERM
  NOMOSX_LAUNCHER_DIR="$WORK" exec node "$WORK/package/build/nomosx.mjs" "$COMMAND" "$@" </dev/null
}

main "$@"
