#!/bin/sh
# get.sh - kick-off for SSNY mesh nodes on Linux (and the macOS placeholder).
#
#   curl -fsSL https://get.success.build | sh
#   curl -fsSL https://get.success.build | sh -s -- --temporary     # args go to the stage script
#
# Detects the platform, downloads the committed stage scripts from the same public folder, refuses them
# unless every SHA256 matches the hash pinned below at publish time, and runs them in order: the mesh
# stage (mesh_add-node.sh, args go to it), then, unless it FAILed, linux_stay-awake.sh and
# linux_standard-apps.sh (with the pinned manifest, so it verifies its own helper files). --dry-run runs
# the later stages with --check. Prompts are read from the terminal (stdin is this script when piped).
# Each stage prints its RESULT; a summary of all of them comes last. Exit: worst of 0 OK, 1 WARN, 2 FAIL.
#
# Source of truth: ssny-us/systems scripts/bootstrap/get.sh (private repo), published by
# scripts/publish-node-bootstrap.sh. No secrets here or in any stage file. Refs: systems#733.
# Windows: irm https://get.success.build | iex
set -eu

BASE="https://success.build/bootstrap"
PUBLISHED="2026-12-05T12:30Z systems@a191316b0"
MANIFEST='windows_mesh-bootstrap.ps1 | dfbad3f710bbe9cc93ec48698bf131ed68040e301c4ef9f6bca5cfb98a39cff7
windows_stay-awake-on-ac.ps1 | 1e16ea6d7084bae60078dfe8f3f2c2a5b6a67648950812e6abbb615297bc54de
windows_standard-apps.ps1 | d62c413c76f36b0fbf438bfe5b3f048ae2cdd50c423a2e61decde05a8abcf932
windows_setup-wsl2.ps1 | 05340a6359897a1013dc4338539fad9c4cc1a2dfcf03664401260a31f05d2ceb
windows_rustdesk-remote-ready.ps1 | ec8a2e34e4b25837166f8221e8411af2a48daad51de88cc809b72525d0206913
windows_wsl-for-user.ps1 | c26756c9679274bcd3da1a5965285f047c090574ee9aec05f6edcf47e0ed8a1e
mesh_add-node.sh | f24423d6b968cbb78b3b8abc451f675f5d4bf89b1ca30f2ed9fa0fecafc12948
linux_stay-awake.sh | e63464f22a24c571de848633dfa3ad6e0905b966f620c85d97a7e1c80ca9977f
linux_standard-apps.sh | 421533fc8d098a18cf78799c5e709ae8c76ac985494605409bbbf3cfcd86de2d
linux_rustdesk-sudoers.sh | 0a2ffce24b5fed9e6ba5c439f4877e3ace2ad468adb32cca938c8387da704d37
windows_onboard-mesh.ps1 | 8103a409fc3b4d2b98612ca5e3c79f42e7110a02f6e81d717d9aacf5b518f584
windows_enable-mesh-ssh.ps1 | 5ed1eec5c171b6edb6985ae23d89b0995d4f578d3546af4c8352853544b9bbc2
windows_setup-operator-ssh.ps1 | af91274c35ea67d170940ede1853fb1ed50548406d40a634f5bb27d307948f4a
config/sublime/User/Preferences.sublime-settings | 6b2339ce572543f78ac3de4a251fb4e1168fa1484e92a2b4c73a61a29c3d4a3e'

# Results report (systems#737): encrypted to this public key (filled at publish time; empty = reporting off).
# Only a run given a join key reports: stage results, and the end of the log for a stage that did not finish
# OK. Never keys or passwords.
REPORT_KID='k202612'
REPORT_PEM='-----BEGIN PUBLIC KEY-----
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAvcjUMtiVD0frBl0Zd20D
BqC4aA42Lis5wo4rNtAUzPN/jI/rZsodY5jHgah9QDv5prYJ1xlsNbtRaa7eu26B
n5VMB8qsvWnEaPcXXukxbEakXBftOFsvyqC7uGzN3NcbCw5ulK2oWKgfK++MqrGQ
RLzU1Nju22Nz1zOREmIZ+DYgBWkimyp+26z/62lAgoJN2pv/CoMACIWL6G0DqHNW
8Y9mpN3Jan+6/MohLoL5/6JETgVLxKmXGspuwHtbxvJSrLw+1BRAFKlGCMlY21WX
Wxx9c5vx0z77j/ZlCmKelGzip8nGbg6jmrfaOZ4OFrJBiru2NYVfua3hrmMn+hik
AGAEmq58TMEierFMT17oFRMcV3OvmCecdWHGZrXUCsmCFdzQPLCNJ71ELswpYkiC
eBDUWUHwDcEop6u9v0bzydvU58gcgylrPmFDO1jd7NBNNtbyMCF8HOL1JBx2G54R
RY9v/Jn0968705g6xhVZgStJKn6V9VKeQqJkLijxVKlzAgMBAAE=
-----END PUBLIC KEY-----'
REPORT_URL="https://get.success.build/report"
START_TS=$(date +%s)

say() { printf '%s\n' "$*"; }
die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; }
pinned() { printf '%s\n' "$MANIFEST" | awk -F' *[|] *' -v n="$1" '$1==n {print tolower($2)}'; }

say ""
say "SSNY mesh node bootstrap"
say "  published $PUBLISHED  |  this machine: $(hostname) ($(uname -sm))"
case "$MANIFEST$PUBLISHED" in *__*) die "this is the unpublished source of get.sh (no pinned hashes); use $BASE/get.sh" ;; esac

os=$(uname -s)
stage=""; later=""
case "$os" in
  Linux)
    [ -r /etc/os-release ] && . /etc/os-release
    case "${ID:-}:${ID_LIKE:-}" in
      *debian*|*ubuntu*) stage="mesh_add-node.sh"; later="linux_stay-awake.sh linux_standard-apps.sh" ;;
      *) die "Linux distro '${ID:-unknown}' not supported yet (Debian/Ubuntu only; systems#68)" ;;
    esac
    say "  target: mesh node (Headscale, Tailscale pinned to the fleet version) via $stage; asks for a mesh name,"
    say "          and a one-time key only if it is not on the mesh yet. Then kept awake on AC (laptops/desktops)"
    say "          and the standard apps (desktops: Sublime Text, Obsidian, RustDesk on our relay)."
    ;;
  Darwin) die "macOS: not scripted yet (join with the Tailscale app pointed at https://hs.success.build; systems#68)" ;;
  *) die "unsupported OS '$os'" ;;
esac

dir=$(mktemp -d)
trap 'rm -rf "$dir"' EXIT
# Download and verify every stage before anything runs; a mismatch stops the whole run.
fetch() {
  want=$(pinned "$1")
  [ -n "$want" ] || die "no pinned hash for $1"
  curl -fsSL "$BASE/$1" -o "$dir/$1" || die "download failed: $BASE/$1"
  got=$(sha256sum "$dir/$1" | awk '{print $1}')
  [ "$got" = "$want" ] || die "SHA256 mismatch for $1: got $got, pinned $want. Not running it."
  say "  $1 verified (sha256 $(printf '%s' "$got" | cut -c1-16)...)"
}
for s in $stage $later; do fetch "$s"; done
# The pinned manifest goes along, so the apps stage verifies its helper files (config, sudoers) against it.
printf '%s\n' "$MANIFEST" > "$dir/manifest-pinned.txt"
say ""
# Prompts come from the terminal when there is one; [ -r /dev/tty ] is true even without a controlling
# terminal (cron, CI), so test by actually opening it.
run() { if (: </dev/tty) 2>/dev/null; then bash "$@" </dev/tty; else bash "$@"; fi; }
level() { case "$1" in 0) echo OK ;; 1) echo WARN ;; *) echo FAIL ;; esac; }

rc=0; run "$dir/$stage" "$@" || rc=$?
summary="mesh:$rc"
check=""; skip=""
for a in "$@"; do
  case "$a" in
    --uninstall|--help|-h) skip="not run with $a" ;;
    --dry-run) check="--check" ;;
  esac
done
if [ -n "$later" ] && [ -z "$skip" ]; then
  if [ "$rc" -ge 2 ]; then
    say ""; say "Later stages skipped: the mesh setup did not finish OK (exit $rc). Fix that and run the same command again."
  else
    r=0; run "$dir/linux_stay-awake.sh" $check || r=$?; summary="$summary stay-awake:$r"
    r=0; run "$dir/linux_standard-apps.sh" --manifest-file "$dir/manifest-pinned.txt" --base "$BASE" $check || r=$?
    summary="$summary apps:$r"
  fi
fi

worst=0
say ""
for x in $summary; do
  n=${x%%:*}; c=${x##*:}
  say "RESULT ($n): $(level "$c")"
  [ "$c" -gt "$worst" ] && worst=$c
done
[ -z "$check" ] && [ -z "$skip" ] && say "  details: /var/lib/ssny-mesh/*-result.json and /var/lib/ssny-mesh/reports/"

# --- Report the results to SSNY (encrypted; systems#737) ----------------------------------------------
hex() { od -An -v -tx1 "$1" | tr -d ' \n'; }
seal() {  # $1 = work dir holding pub.pem and pt; writes env (the JSON envelope)
  d=$1
  openssl rand 64 > "$d/k" && head -c 32 "$d/k" > "$d/ke" && tail -c 32 "$d/k" > "$d/km" && openssl rand 16 > "$d/iv" || return 1
  openssl pkeyutl -encrypt -pubin -inkey "$d/pub.pem" -pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256 \
    -pkeyopt rsa_mgf1_md:sha256 -in "$d/k" -out "$d/ek" 2>/dev/null || return 1
  openssl enc -aes-256-cbc -K "$(hex "$d/ke")" -iv "$(hex "$d/iv")" -in "$d/pt" -out "$d/ct" || return 1
  mac=$(cat "$d/iv" "$d/ct" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$(hex "$d/km")" -binary | base64 -w0) || return 1
  printf '{"v":1,"kid":"%s","ek":"%s","iv":"%s","ct":"%s","mac":"%s"}' "$REPORT_KID" "$(base64 -w0 < "$d/ek")" \
    "$(base64 -w0 < "$d/iv")" "$(base64 -w0 < "$d/ct")" "$mac" > "$d/env"
  rm -f "$d/k" "$d/ke" "$d/km"
}
report_send() {
  case "$REPORT_PEM" in *"BEGIN PUBLIC KEY"*) ;; *) return 0 ;; esac
  tf=/var/lib/ssny-mesh/report-token.txt
  [ -r "$tf" ] && [ "$(stat -c %Y "$tf")" -ge "$START_TS" ] || return 0
  tok=$(tr -dc '0-9a-f' < "$tf"); [ "${#tok}" -eq 40 ] || return 0
  command -v openssl >/dev/null 2>&1 || { say "  (results not sent: openssl is not installed)"; return 0; }
  rd=$(mktemp -d); chmod 700 "$rd"; printf '%s\n' "$REPORT_PEM" > "$rd/pub.pem"
  run=$(cat /proc/sys/kernel/random/uuid); seq=0; sent=0
  for x in $summary; do
    n=${x%%:*}; c=${x##*:}; seq=$((seq + 1))
    rf="/var/lib/ssny-mesh/$n-result.json"; doc=""
    [ -r "$rf" ] && [ "$(stat -c %Y "$rf")" -ge "$START_TS" ] && doc=$(base64 -w0 < "$rf")
    tl=""
    if [ "$c" -ne 0 ]; then
      lg=$(ls -t /var/lib/ssny-mesh/reports/"$n"-*.log 2>/dev/null | head -1)
      [ -n "$lg" ] && [ -r "$lg" ] && tl=$(tail -n 80 "$lg" | base64 -w0)
    fi
    printf '{"v":1,"token":"%s","run":"%s","seq":%d,"ts":"%s","computer":"%s","label":"%s","result":"%s","doc_b64":"%s","log_tail_b64":"%s"}' \
      "$tok" "$run" "$seq" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$(hostname -s)" "$n" "$(level "$c")" "$doc" "$tl" > "$rd/pt"
    if seal "$rd" && curl -fsS -m 20 -H 'Content-Type: application/json' --data-binary @"$rd/env" "$REPORT_URL" >/dev/null 2>&1; then
      sent=$((sent + 1))
    else
      say "  (report $n not sent)"
    fi
  done
  rm -rf "$rd"
  sudo -n rm -f "$tf" 2>/dev/null || true
  [ "$sent" -gt 0 ] && say "Results sent to SSNY (encrypted): $sent report(s). Nothing to copy back."
  return 0
}
[ -z "$check" ] && [ -z "$skip" ] && { report_send || true; }

[ "$worst" -gt 2 ] && worst=2
exit "$worst"
