#!/usr/bin/env bash
# Download first and inspect if you do not want to execute a remote bootstrap.
# Kept inside a function: an incomplete curl | bash download cannot run half a setup.
smem_install() (
  set -euo pipefail
  command -v node >/dev/null 2>&1 || { echo 'Install Node.js 22.13+ and Pi first: https://nodejs.org / https://pi.dev' >&2; exit 1; }
  command -v curl >/dev/null 2>&1 || { echo 'curl is required.' >&2; exit 1; }
  node -e 'const [a,b]=process.versions.node.split(".").map(Number); if(a<22 || (a===22 && b<13)){console.error("Node.js 22.13+ is required");process.exit(1)}'
  umask 077
  local work expected interactive=1 arg
  work=$(mktemp -d "${TMPDIR:-/tmp}/smem-install.XXXXXXXX")
  trap 'rm -rf -- "$work"' EXIT
  trap 'exit 130' INT
  trap 'exit 143' TERM HUP
  expected='ee0c0f2232575182028fe9811da8c53cff6a8c6157ee14df3b2600886ac8ff0e'
  [[ $expected =~ ^[a-f0-9]{64}$ ]] || { echo 'Unbuilt bootstrap; use the published install.sh.' >&2; exit 1; }
  echo 'Downloading SMEM installer...'
  curl --proto '=https' --proto-redir '=https' -fLsS --connect-timeout 15 --max-time 120 https://smem.dev/install.mjs -o "$work/install.mjs"
  node --input-type=module - "$work/install.mjs" "$expected" <<'NODE'
import {readFileSync} from 'node:fs';
import {createHash} from 'node:crypto';
if(createHash('sha256').update(readFileSync(process.argv[2])).digest('hex')!==process.argv[3]) {
  console.error('Installer checksum mismatch. Nothing executed; download the bootstrap again.');process.exit(1);
}
NODE
  for arg in "$@"; do
    case "$arg" in --apply|--dry-run|--help|-h) interactive=0 ;; esac
  done
  # A pipe carries this shell script, not answers to the Node wizard.
  if (( interactive )) && [[ ! -t 0 ]]; then
    if ! { exec </dev/tty; } 2>/dev/null; then
      echo 'No terminal. Use --dry-run, or --apply with --token-file / SMEM_TOKEN.' >&2
      exit 1
    fi
  fi
  node "$work/install.mjs" --interactive "$@"
)
smem_install "$@"
