#!/bin/sh
# written by White Brood (Gemini 4 Carbon (High)) [KAAL:E6@2026-11-30T06:51:27Z · sha256:e67cf11a6766f991]
# updated by White Brood (Gemini 4 Carbon (High)) [KAAL:E6@2026-11-30T06:55:24Z · prev:e67cf11a6766f991 -> sha256:c42949a46e4ed417]
# MasiDyn CLI installer (POSIX). Fetches the picker + client, verifies SHA-256
# checksums in a secure staging directory, and puts `masidyn` on your PATH.
# It never automates credentials or runs privileged operations.
#
#   curl -fsSL https://masidyn.dev/install.sh | sh
#
# Env overrides:
#   MASIDYN_HOME        install dir           (default: $HOME/.masidyn)
#   MASIDYN_BIN         launcher dir on PATH  (default: $HOME/.local/bin)
#   MASIDYN_WEIGHTS_DIR weights manifest dir  (default: $HOME_DIR/weights)
#   MASIDYN_ORIGIN      download origin       (default: https://masidyn.dev)
set -eu

ORIGIN="${MASIDYN_ORIGIN:-https://masidyn.dev}"
ORIGIN="${ORIGIN%/}"
HOME_DIR="${MASIDYN_HOME:-$HOME/.masidyn}"
BIN_DIR="${MASIDYN_BIN:-$HOME/.local/bin}"
WEIGHTS_DIR="${MASIDYN_WEIGHTS_DIR:-$HOME_DIR/weights}"

say() { printf '  %s\n' "$*"; }
die() { printf 'error: %s\n' "$*" >&2; exit 1; }

# 1. Require Python 3 (the runtime, CLI, and client are stdlib-only Python).
PY=""
for c in python3 python py; do
  if command -v "$c" >/dev/null 2>&1; then PY="$c"; break; fi
done
[ -n "$PY" ] || die "Python 3 is required but was not found. Install Python 3, then re-run."
say "using python: $($PY --version 2>&1)"

# 2. Pick a downloader and hash helper.
fetch() { # fetch <url> <dest>
  if command -v curl >/dev/null 2>&1; then curl -fsSL "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then wget -qO "$2" "$1"
  else die "need curl or wget to download files"; fi
}

sha256_file() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}' | tr 'A-F' 'a-f' | tr -dc '0-9a-f'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{print $1}' | tr 'A-F' 'a-f' | tr -dc '0-9a-f'
  else
    "$PY" -c 'import hashlib,sys; print(hashlib.sha256(open(sys.argv[1],"rb").read()).hexdigest())' "$1" | tr 'A-F' 'a-f' | tr -dc '0-9a-f'
  fi
}

lookup_sha256() {
  _rel="$1"
  _base="$2"
  _sums="$3"
  awk -v rel="$_rel" -v base="$_base" '
    BEGIN { found = ""; base_found = "" }
    {
      sub(/\r$/, "")
      line = $0
      sub(/^[ \t]+/, "", line)
      if (line == "" || substr(line, 1, 1) == "#") next
      sp = match(line, /[ \t]+/)
      if (sp == 0) next
      h = substr(line, 1, sp - 1)
      if (length(h) != 64 || h !~ /^[a-fA-F0-9]+$/) next
      h = tolower(h)
      rest = substr(line, sp + RLENGTH)
      if (substr(rest, 1, 1) == "*") rest = substr(rest, 2)
      sub(/^[ \t]+/, "", rest)
      sub(/[ \t]+$/, "", rest)
      gsub(/\\/, "/", rest)
      while (substr(rest, 1, 2) == "./") rest = substr(rest, 3)
      sub(/^\/+/, "", rest)
      if (rest == rel && found == "") found = h
      else if (rest == base && base_found == "") base_found = h
    }
    END {
      if (found != "") print found
      else if (base_found != "") print base_found
    }
  ' "$_sums"
}

verify_staged() {
  _file="$1"
  _rel="$2"
  _base="${_rel##*/}"
  _sums="$3"
  [ -f "$_file" ] || die "SHA-256 verification failed for $_rel (missing staged file)"
  _expected="$(lookup_sha256 "$_rel" "$_base" "$_sums")"
  [ -n "$_expected" ] || die "SHA-256 verification failed for $_rel (missing checksum entry)"
  _actual="$(sha256_file "$_file")"
  [ "$_actual" = "$_expected" ] || die "SHA-256 verification failed for $_rel (expected $_expected, got $_actual)"
}

sh_quote() {
  _s="$1"
  printf "'"
  while :; do
    case "$_s" in
      *"'"*)
        printf '%s' "${_s%%"'"*}"
        printf "'\\''"
        _s="${_s#*"'"}"
        ;;
      *)
        printf '%s' "$_s"
        break
        ;;
    esac
  done
  printf "'"
}

# 3. Create secure temporary staging dir and verify all artifacts before touching $HOME_DIR or $BIN_DIR.
STAGE_DIR="$(mktemp -d 2>/dev/null || mktemp -d -t masidyn)"
[ -n "$STAGE_DIR" ] && [ -d "$STAGE_DIR" ] || die "could not create staging directory"
trap 'rm -rf "$STAGE_DIR"' EXIT INT TERM

SUMS_FILE="$STAGE_DIR/SHA256SUMS.txt"
if ! fetch "$ORIGIN/SHA256SUMS.txt" "$SUMS_FILE" 2>/dev/null; then
  rm -f "$SUMS_FILE"
  fetch "$ORIGIN/releases/SHA256SUMS.txt" "$SUMS_FILE" 2>/dev/null || die "SHA-256 verification failed for SHA256SUMS.txt (could not download manifest)"
fi
[ -s "$SUMS_FILE" ] || die "SHA-256 verification failed for SHA256SUMS.txt (manifest is empty)"

say "downloading and verifying masidyn CLI + hardware-tier router in staging directory"
fetch "$ORIGIN/clients/masidyn_pick.py"             "$STAGE_DIR/masidyn_pick.py"             || die "failed to download clients/masidyn_pick.py"
verify_staged "$STAGE_DIR/masidyn_pick.py"          "clients/masidyn_pick.py"                "$SUMS_FILE"

fetch "$ORIGIN/clients/masidyn_client.py"           "$STAGE_DIR/masidyn_client.py"           || die "failed to download clients/masidyn_client.py"
verify_staged "$STAGE_DIR/masidyn_client.py"        "clients/masidyn_client.py"              "$SUMS_FILE"

fetch "$ORIGIN/clients/masidyn_hardware_tier.py"    "$STAGE_DIR/masidyn_hardware_tier.py"    || die "failed to download clients/masidyn_hardware_tier.py"
verify_staged "$STAGE_DIR/masidyn_hardware_tier.py" "clients/masidyn_hardware_tier.py"       "$SUMS_FILE"

fetch "$ORIGIN/releases/base_weights_manifest.json" "$STAGE_DIR/base_weights_manifest.json"  || die "failed to download releases/base_weights_manifest.json"
verify_staged "$STAGE_DIR/base_weights_manifest.json" "releases/base_weights_manifest.json"  "$SUMS_FILE"

# 4. Verify the platform-specific installer before changing any install files.
# A missing or invalid child download must not replace an existing launcher.
CROSTINI=0
if [ -f /dev/wl0 ] || [ -f /etc/apt/sources.list.d/cros.list ] || [ "$(hostname 2>/dev/null || true)" = "penguin" ]; then
  CROSTINI=1
  say "detected Chromebook Crostini (penguin) container — verifying install-chromebook.sh"
  fetch "$ORIGIN/install-chromebook.sh" "$STAGE_DIR/install-chromebook.sh" || die "failed to download install-chromebook.sh"
  verify_staged "$STAGE_DIR/install-chromebook.sh" "install-chromebook.sh" "$SUMS_FILE"
fi

# 5. Promote verified files into $HOME_DIR / $WEIGHTS_DIR and write launcher safely.
mkdir -p "$HOME_DIR" "$BIN_DIR" "$WEIGHTS_DIR"
mv -f "$STAGE_DIR/masidyn_pick.py"             "$HOME_DIR/masidyn_pick.py"
mv -f "$STAGE_DIR/masidyn_client.py"           "$HOME_DIR/masidyn_client.py"
mv -f "$STAGE_DIR/masidyn_hardware_tier.py"    "$HOME_DIR/masidyn_hardware_tier.py"
mv -f "$STAGE_DIR/base_weights_manifest.json"  "$WEIGHTS_DIR/base_weights_manifest.json"

LAUNCHER="$BIN_DIR/masidyn"
STAGED_LAUNCHER="$STAGE_DIR/masidyn"
Q_HOME="$(sh_quote "$HOME_DIR")"
Q_PY="$(sh_quote "$PY")"
cat > "$STAGED_LAUNCHER" <<'EOF'
#!/bin/sh
# MasiDyn launcher (generated by install.sh)
EOF
printf 'if [ -z "${MASIDYN_HOME:-}" ]; then\n  MASIDYN_HOME=%s\nfi\n' "$Q_HOME" >> "$STAGED_LAUNCHER"
printf 'PY=%s\n' "$Q_PY" >> "$STAGED_LAUNCHER"
cat >> "$STAGED_LAUNCHER" <<'EOF'
cmd="${1:-pick}"
case "$cmd" in
  pick|"") shift 2>/dev/null || true; exec "$PY" "$MASIDYN_HOME/masidyn_pick.py" "$@" ;;
  *)       exec "$PY" "$MASIDYN_HOME/masidyn_pick.py" "$@" ;;
esac
EOF
chmod +x "$STAGED_LAUNCHER"
mv -f "$STAGED_LAUNCHER" "$LAUNCHER"
say "installed launcher: $LAUNCHER"

# Execute only the previously verified child after publishing the generic launcher.
if [ "$CROSTINI" = 1 ]; then
  if [ -z "${MASIDYN_DEV_ORIGIN:-}" ] && [ "$ORIGIN" != "https://masidyn.com" ]; then
    MASIDYN_DEV_ORIGIN="$ORIGIN" sh "$STAGE_DIR/install-chromebook.sh"
  else
    sh "$STAGE_DIR/install-chromebook.sh"
  fi
fi

# 6. PATH hint.
case ":$PATH:" in
  *":$BIN_DIR:"*) : ;;
  *) say "NOTE: add $BIN_DIR to your PATH:"
     say "  export PATH=\"$BIN_DIR:\$PATH\"" ;;
esac

printf '\n  MasiDyn CLI installed. Try:  masidyn pick\n'
printf '  (Auto-discovers local MasiDyn via .masidyn/runtime/ports/beam-control.json Port-0 handshake.)\n\n'
