#!/bin/sh
# a2k-lite -- the barebones A2000 support kit for Linux, macOS and Android (Termux). Command line only.
#
# What it puts on this machine (nothing else, no screen):
#   1. OpenSSH server: kept as it is when one is already running; installed only when there is none.
#   2. dumbpipe (an iroh tunnel): forwards iroh connections to this machine's own SSH server, so a
#      supporter can reach it behind any router without opening a port. Always on, restarts at boot.
#   3. One SSH key line per supporter in ~/.ssh/authorized_keys, labelled "a2k-op:<name>".
#   4. Claude Code (no account is signed in): Anthropic's installer on Linux and macOS; on Android npm
#      with Termux's Node.js. Kept when it is already there; uninstall never removes it.
# Then it registers the machine by itself, like the Windows field kit does:
#   - the visit registry (relay.llmsecrets.com /visits/agent-enroll): host, device id, iroh endpoint id,
#     so the machine shows in GET /visits/devices and a supporter can open a visit for it by name;
#   - the enrollment inbox (get.llmsecrets.com/a2000rec/ingest): the connect details (iroh ticket, SSH
#     user and port), which a2k_enroll.py saves into scrt4. Nobody reads anything over the phone.
#
# Commands (after install the script is also at ~/.local/bin/a2k-lite, or $PREFIX/bin/a2k-lite on Termux):
#   a2k-lite install     show the plan, ask YES, install, start, self-test, register
#   a2k-lite status      is the tunnel running, is SSH answering, what was registered (exit 1 when not running)
#   a2k-lite register    send the registration again (it is also sent by itself when the ticket changes)
#   a2k-lite start | stop | restart
#   a2k-lite ticket      print the connect ticket (only for sending it by hand when registering failed)
#   a2k-lite update-claude   install the current Claude Code again (on Android it does not update itself)
#   a2k-lite uninstall   remove what this kit added; never removes or turns off the SSH server
#   a2k-lite run         the tunnel in the foreground (what the boot service runs)
#
# Settings (environment): A2K_LITE_YES=1 (no question; for scripted installs), A2K_LITE_HOME,
#   A2K_LITE_SSH_PORT, A2K_LITE_HOST (the name it registers under), A2K_LITE_NO_REGISTER=1,
#   A2K_LITE_SKIP=claude (leave Claude Code out).
#   For tests only: A2K_LITE_REGISTRY_URL, A2K_LITE_INGEST_URL, A2K_LITE_ENROLL_KEY,
#   A2K_LITE_OPERATOR_KEYS_FILE (lines "<name> <ssh public key>"), A2K_LITE_DUMBPIPE_BIN (a local copy).
#
# POSIX sh: runs under dash (Debian/Ubuntu), bash (most Linux, Termux) and macOS /bin/sh.
set -u

VERSION=0.2.0
DUMBPIPE_VERSION=0.40.1
# write-only key: the inbox can only APPEND, the registry route is add-only. It is already in the public
# Windows installer and recorder, so having it here adds nothing.
ENROLL_KEY_DEFAULT=a2kw_43b3c3e0aefd98412b470f1edaeb2bc0c9f1ad691a7fafbc
# settings the install was run with are kept in $A2K_HOME/config, so the boot service (which starts
# with an empty environment) and later commands use the same registry, port and name
SETTINGS='A2K_LITE_SKIP A2K_LITE_REGISTRY_URL A2K_LITE_INGEST_URL A2K_LITE_ENROLL_KEY A2K_LITE_SSH_PORT A2K_LITE_HOST A2K_LITE_NO_REGISTER A2K_LITE_OPERATOR_KEYS_FILE A2K_LITE_DUMBPIPE_BASE'
# One SSH key per SUPPORTER (same list as dist/onboard/setup.ps1 in the see repo). Add supporters here.
OPERATOR_KEYS='josh ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHga5YRgFl6yB9WvrHLGbeG19/b+a9cozPdRvvr/nMvz'

# ---------------------------------------------------------------- small helpers
say()  { printf '%s\n' "$*"; }
warn() { printf '  ! %s\n' "$*" >&2; }
die()  { printf '\n  STOPPED: %s\n\n' "$*" >&2; exit 1; }
have() { command -v "$1" >/dev/null 2>&1; }
now_iso() { date -u +%Y-%m-%dT%H:%M:%SZ; }
lower() { printf '%s' "$1" | tr 'A-Z' 'a-z'; }

sha256_file() {
  if have sha256sum; then sha256sum "$1" | awk '{print $1}'
  elif have shasum; then shasum -a 256 "$1" | awk '{print $1}'
  else openssl dgst -sha256 "$1" | awk '{print $NF}'; fi
}
sha256_text() {
  if have sha256sum; then printf '%s' "$1" | sha256sum | awk '{print $1}'
  elif have shasum; then printf '%s' "$1" | shasum -a 256 | awk '{print $1}'
  else printf '%s' "$1" | openssl dgst -sha256 | awk '{print $NF}'; fi
}
# a JSON string literal: quotes and backslashes escaped, control characters turned into spaces
json_str() {
  printf '"%s"' "$(printf '%s' "$1" | tr '\000-\037' ' ' | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g')"
}
rand_port() { awk -v s="$$" 'BEGIN { srand(s + srand()); print 41000 + int(rand() * 7000) }'; }

# run "$@" with a time limit in seconds (macOS has no `timeout`); returns the command's status or 124
with_timeout() {
  _t=$1; shift
  "$@" &
  _p=$!
  ( sleep "$_t"; kill "$_p" 2>/dev/null ) >/dev/null 2>&1 &
  _w=$!
  wait "$_p"; _rc=$?
  kill "$_w" 2>/dev/null; wait "$_w" 2>/dev/null
  [ $_rc -gt 128 ] && return 124
  return $_rc
}

# does an SSH server answer on 127.0.0.1:<port>? (it sends its host key)
ssh_answers() {
  have ssh-keyscan || return 1
  [ -n "$(ssh-keyscan -T 3 -p "$1" 127.0.0.1 2>/dev/null)" ]
}

# ---------------------------------------------------------------- platform
detect_platform() {
  OS=''; ARCH=$(uname -m)
  if [ -n "${TERMUX_VERSION:-}" ] || case ${PREFIX:-} in *com.termux*) true ;; *) false ;; esac; then OS=android
  else
    case $(uname -s) in
      Linux) OS=linux ;;
      Darwin) OS=macos ;;
      *) die "this kit is for Linux, macOS and Android (Termux). This system says '$(uname -s)'. On Windows use the field kit." ;;
    esac
  fi
  if [ "$(id -u)" = 0 ]; then SUDO=''; elif have sudo; then SUDO=sudo; else SUDO=none; fi
  RUN_USER=$(id -un)
  # the home sshd uses for this account (from the user database; $HOME can differ under sudo -E or in containers)
  SSH_HOME=''
  case $OS in
    android) SSH_HOME=$HOME ;;
    macos) SSH_HOME=$(dscl . -read "/Users/$RUN_USER" NFSHomeDirectory 2>/dev/null | awk '{print $2}') ;;
    *) SSH_HOME=$(getent passwd "$RUN_USER" 2>/dev/null | cut -d: -f6) ;;
  esac
  [ -n "$SSH_HOME" ] && [ -d "$SSH_HOME" ] || SSH_HOME=$HOME
  AK=$SSH_HOME/.ssh/authorized_keys
  A2K_HOME=${A2K_LITE_HOME:-$HOME/.a2k-lite}
  # the install's settings, unless this command was given its own
  if [ -f "$A2K_HOME/config" ]; then
    while IFS='=' read -r _k _v; do
      case " $SETTINGS " in *" $_k "*) eval "_cur=\${$_k:-}"; [ -z "$_cur" ] && eval "$_k=\$_v" ;; esac
    done < "$A2K_HOME/config"
  fi
  DUMBPIPE_BASE=${A2K_LITE_DUMBPIPE_BASE:-https://github.com/n0-computer/dumbpipe/releases/download/v$DUMBPIPE_VERSION}
  REGISTRY_URL=${A2K_LITE_REGISTRY_URL:-https://relay.llmsecrets.com}
  INGEST_URL=${A2K_LITE_INGEST_URL:-https://get.llmsecrets.com/a2000rec/ingest}
  ENROLL_KEY=${A2K_LITE_ENROLL_KEY:-$ENROLL_KEY_DEFAULT}
  if [ $OS = android ]; then
    BIN_LINK=${PREFIX:-/data/data/com.termux/files/usr}/bin/a2k-lite
    SSH_PORT=${A2K_LITE_SSH_PORT:-8022}
  else
    BIN_LINK=$HOME/.local/bin/a2k-lite
    SSH_PORT=${A2K_LITE_SSH_PORT:-22}
  fi
  DP=$A2K_HOME/bin/dumbpipe
  SELF=$A2K_HOME/bin/a2k-lite
  LOG=$A2K_HOME/listener.log
}

os_name() {
  case $OS in
    linux) ( . /etc/os-release 2>/dev/null && printf '%s' "${PRETTY_NAME:-Linux}" ) || printf 'Linux' ;;
    macos) printf 'macOS %s' "$(sw_vers -productVersion 2>/dev/null)" ;;
    android)
      _rel=$(getprop ro.build.version.release 2>/dev/null)
      _mod="$(getprop ro.product.manufacturer 2>/dev/null) $(getprop ro.product.model 2>/dev/null)"
      _mod=$(printf '%s' "$_mod" | sed 's/^ *//;s/ *$//')
      printf 'Android%s%s, Termux%s' "${_rel:+ $_rel}" "${_mod:+ ($_mod)}" "${TERMUX_VERSION:+ $TERMUX_VERSION}" ;;
  esac
  printf ' %s' "$ARCH"
}

# the name this machine registers under: upper case letters, digits and dashes, at most 40
host_name() {
  if [ -n "${A2K_LITE_HOST:-}" ]; then _h=$A2K_LITE_HOST
  else
    case $OS in
      macos) _h=$(scutil --get LocalHostName 2>/dev/null || uname -n) ;;
      android) _h="ANDROID-$(getprop ro.product.model 2>/dev/null)" ;;
      *) _h=$(uname -n) ;;
    esac
    _h=${_h%%.*}
  fi
  _h=$(printf '%s' "$_h" | tr 'a-z ' 'A-Z-' | tr -cd 'A-Z0-9_-' | cut -c1-40)
  [ -n "$_h" ] && [ "$_h" != ANDROID- ] || _h="$(printf '%s' "$OS" | tr 'a-z' 'A-Z')-$(device_id | cut -c5-12 | tr 'a-z' 'A-Z')"
  printf '%s' "$_h"
}

# 'dev_' + first 16 hex of SHA-256('a2k-device:' + machine id, lower case): the same formula as the
# Windows kit (MachineGuid) and a2k-agent on Linux (/etc/machine-id). Android and machines without an
# id get a random one, kept in ~/.a2k-device-id (outside the kit folder, so a reinstall keeps it).
device_id() {
  _m=''
  case $OS in
    linux) for f in /etc/machine-id /var/lib/dbus/machine-id; do [ -s $f ] && { _m=$(cat $f); break; }; done ;;
    macos) _m=$(ioreg -rd1 -c IOPlatformExpertDevice 2>/dev/null | awk -F'"' '/IOPlatformUUID/ {print $4}') ;;
  esac
  if [ -z "$_m" ]; then
    _f=$HOME/.a2k-device-id
    [ -s "$_f" ] || od -An -tx1 -N16 /dev/urandom | tr -d ' \n' > "$_f"
    _m=$(cat "$_f")
  fi
  _m=$(lower "$(printf '%s' "$_m" | tr -d ' \r\n')")
  printf 'dev_%s' "$(sha256_text "a2k-device:$_m" | cut -c1-16)"
}

# the endpoint id (64 hex, public) inside a dumbpipe ticket: "endpoint" + base32 of
# [0x00, 32-byte public key, addresses...]. Checked in the tests against the key made from the secret.
endpoint_from_ticket() {
  printf '%s' "$1" | sed 's/^endpoint//' | awk '
    BEGIN { a = "abcdefghijklmnopqrstuvwxyz234567"; h = "0123456789abcdef" }
    { buf = 0; nb = 0; n = 0; out = ""
      for (i = 1; i <= length($0) && n < 33; i++) {
        v = index(a, substr($0, i, 1)) - 1
        if (v < 0) exit 1
        buf = buf * 32 + v; nb += 5
        if (nb >= 8) {
          nb -= 8; p = 2 ^ nb; b = int(buf / p); buf = buf - b * p
          if (n == 0 && b != 0) exit 1
          if (n >= 1) out = out substr(h, int(b / 16) + 1, 1) substr(h, b % 16 + 1, 1)
          n++
        }
      }
      if (n < 33) exit 1
      print out }'
}

# ---------------------------------------------------------------- pieces of the install
need_tools() {
  _miss=''
  for t in curl tar gzip base64 awk sed od ssh ssh-keygen ssh-keyscan; do have $t || _miss="$_miss $t"; done
  [ -z "$_miss" ] && return 0
  if [ $OS = android ]; then
    say "  installing tools:$_miss"
    pkg install -y curl tar gzip coreutils gawk sed openssh >/dev/null 2>&1 || die "pkg install failed. Termux must come from F-Droid or GitHub (the Google Play copy is too old to install packages)."
    return 0
  fi
  # on Linux, only the SSH client tools missing: the OpenSSH packages bring them
  if [ $OS = linux ] && [ -z "$(printf '%s' "$_miss" | sed 's/ ssh-keyscan//; s/ ssh-keygen//; s/ ssh//')" ]; then
    say '  installing the OpenSSH tools ...'; pkg_install_linux; return 0
  fi
  die "missing tools:$_miss. Install them and run this again."
}

pkg_install_linux() {
  # $1 = what to install, by package manager
  [ "$SUDO" = none ] && die "OpenSSH server is not installed and there is no sudo. Install openssh-server yourself, then run this again."
  if have apt-get; then $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server openssh-client >/dev/null 2>&1 || { $SUDO apt-get update >/dev/null 2>&1; $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y openssh-server openssh-client >/dev/null 2>&1; }
  elif have dnf; then $SUDO dnf install -y openssh-server openssh-clients >/dev/null 2>&1
  elif have yum; then $SUDO yum install -y openssh-server openssh-clients >/dev/null 2>&1
  elif have zypper; then $SUDO zypper --non-interactive install openssh >/dev/null 2>&1
  elif have pacman; then $SUDO pacman -S --noconfirm --needed openssh >/dev/null 2>&1
  elif have apk; then $SUDO apk add openssh-server >/dev/null 2>&1 || $SUDO apk add openssh >/dev/null 2>&1
  else die "no known package manager. Install an OpenSSH server yourself, then run this again."; fi
}

start_sshd_linux() {
  if have systemctl && [ -d /run/systemd/system ]; then
    $SUDO systemctl enable --now ssh >/dev/null 2>&1 || $SUDO systemctl enable --now sshd >/dev/null 2>&1
  elif have rc-service; then $SUDO rc-update add sshd default >/dev/null 2>&1; $SUDO rc-service sshd start >/dev/null 2>&1
  elif have service; then $SUDO service ssh start >/dev/null 2>&1 || $SUDO service sshd start >/dev/null 2>&1
  fi
  ssh_answers "$SSH_PORT" && return 0
  # no service manager (containers): host keys + the daemon itself
  _sd=$(command -v sshd || ls /usr/sbin/sshd 2>/dev/null)
  [ -n "$_sd" ] || return 1
  $SUDO ssh-keygen -A >/dev/null 2>&1; $SUDO mkdir -p /run/sshd 2>/dev/null; $SUDO "$_sd" >/dev/null 2>&1
}

# OpenSSH 9.8 and later shut out an address for a while after failed or unfinished connections
# (PerSourcePenalties). Every supporter arrives through the tunnel from 127.0.0.1, so one bad sign-in
# would shut ALL of them out. This setting exempts loopback, nothing else.
penalties_apply() {
  set -- $(ssh -V 2>&1 | sed -n 's/^OpenSSH_\([0-9][0-9]*\)\.\([0-9][0-9]*\).*/\1 \2/p')
  [ -n "${1:-}" ] && { [ "$1" -gt 9 ] || { [ "$1" = 9 ] && [ "$2" -ge 8 ]; }; }
}
EXEMPT_LINE='PerSourcePenaltyExemptList 127.0.0.1,::1'
# only for an SSH server this kit installed or turned on (or Termux's own); a server that was already
# running is never changed. The setting is checked with sshd -t and taken back if sshd refuses it.
exempt_loopback() {
  penalties_apply || return 0
  _sd=$(command -v sshd || ls /usr/sbin/sshd 2>/dev/null)
  case $OS in
    android)
      _cf=${PREFIX:-/data/data/com.termux/files/usr}/etc/ssh/sshd_config
      grep -q '^PerSourcePenaltyExemptList' "$_cf" 2>/dev/null && return 0
      printf '\n# a2k-lite: supporters all arrive from 127.0.0.1 through the tunnel\n%s\n' "$EXEMPT_LINE" >> "$_cf"
      if sshd -t >/dev/null 2>&1; then pkill -x sshd 2>/dev/null; sleep 1; sshd >/dev/null 2>&1; PENALTY_NOTE='loopback exempt from sign-in penalties'
      else grep -v -e '^# a2k-lite: supporters' -e "^$EXEMPT_LINE\$" "$_cf" > "$_cf.a2k-new" && mv -f "$_cf.a2k-new" "$_cf"; fi ;;
    *)
      _dd=/etc/ssh/sshd_config.d
      [ -d $_dd ] && grep -q '^Include /etc/ssh/sshd_config.d/' /etc/ssh/sshd_config 2>/dev/null || return 0
      printf '# a2k-lite: supporters all arrive from 127.0.0.1 through the tunnel\n%s\n' "$EXEMPT_LINE" | $SUDO tee $_dd/a2k-lite.conf >/dev/null
      if [ -n "$_sd" ] && $SUDO "$_sd" -t >/dev/null 2>&1; then
        PENALTY_NOTE='loopback exempt from sign-in penalties'
        [ $OS = linux ] && { $SUDO systemctl reload ssh >/dev/null 2>&1 || $SUDO systemctl reload sshd >/dev/null 2>&1 || $SUDO pkill -HUP -x sshd 2>/dev/null; }
      else $SUDO rm -f $_dd/a2k-lite.conf; fi ;;
  esac
  return 0
}

ensure_sshd() {
  PENALTY_NOTE=''
  if ssh_answers "$SSH_PORT"; then
    SSHD_STATE="already running on port $SSH_PORT (kept as it is)"
    [ $OS = android ] && { exempt_loopback; [ -n "$PENALTY_NOTE" ] && SSHD_STATE="$SSHD_STATE; $PENALTY_NOTE"; }
    return 0
  fi
  case $OS in
    android)
      have sshd || pkg install -y openssh >/dev/null 2>&1 || die "could not install openssh (pkg install openssh)."
      sshd >/dev/null 2>&1 ;;
    linux)
      if ! have sshd && [ ! -x /usr/sbin/sshd ]; then say "  installing OpenSSH server ..."; pkg_install_linux; fi
      [ "$SUDO" = none ] && die "the SSH server is installed but not running, and there is no sudo to start it."
      start_sshd_linux ;;
    macos)
      [ "$SUDO" = none ] && die "Remote Login (SSH) is off. Turn it on: System Settings > General > Sharing > Remote Login."
      $SUDO systemsetup -f -setremotelogin on >/dev/null 2>&1 || true
      ssh_answers "$SSH_PORT" || $SUDO launchctl load -w /System/Library/LaunchDaemons/ssh.plist >/dev/null 2>&1 || true ;;
  esac
  i=0; while [ $i -lt 10 ]; do ssh_answers "$SSH_PORT" && break; sleep 1; i=$((i + 1)); done
  ssh_answers "$SSH_PORT" || {
    [ $OS = macos ] && die "Remote Login (SSH) did not start. Turn it on: System Settings > General > Sharing > Remote Login, then run this again."
    die "the SSH server does not answer on port $SSH_PORT."
  }
  exempt_loopback
  SSHD_STATE="started on port $SSH_PORT${PENALTY_NOTE:+; $PENALTY_NOTE}"
}

install_dumbpipe() {
  mkdir -p "$A2K_HOME/bin"
  if [ -n "${A2K_LITE_DUMBPIPE_BIN:-}" ]; then cp "$A2K_LITE_DUMBPIPE_BIN" "$DP" && chmod 755 "$DP"; return; fi
  if [ $OS = android ]; then
    # Termux builds dumbpipe itself for every Android CPU (same version), with the DNS settings Android lacks
    have dumbpipe || pkg install -y dumbpipe >/dev/null 2>&1 || die "could not install dumbpipe (pkg install dumbpipe)."
    ln -sf "$(command -v dumbpipe)" "$DP"; return
  fi
  case "$OS-$ARCH" in
    linux-x86_64|linux-amd64) _a=linux-x86_64; _sum=66aee1e249890ee63678dfc8f18ce3671e691673c83bbd72bf9a54c4d32da85c ;;
    linux-aarch64|linux-arm64) _a=linux-aarch64; _sum=1529c49598ac15d9413bf7f29a09c04cf2f5dc3af1b9080a1b50855a77846c47 ;;
    macos-arm64) _a=darwin-aarch64; _sum=e6bd3c9a98ba22e8233ae1f8ba5e2dceb4cbf132dc4d4332589295b702902a27 ;;
    macos-x86_64) _a=darwin-x86_64; _sum=eaa35e228528cbf5fc2a8a07646570f49af6ab1acd35c8f539f150a0cb5d4b0e ;;
    *) die "no dumbpipe build for $OS $ARCH. Supported: Linux x86_64 and arm64, macOS Apple and Intel, Android (Termux, any CPU)." ;;
  esac
  _tmp=$(mktemp -d 2>/dev/null || mktemp -d -t a2klite)
  _tgz=$_tmp/dp.tar.gz
  curl -fsSL -m 300 -o "$_tgz" "$DUMBPIPE_BASE/dumbpipe-v$DUMBPIPE_VERSION-$_a.tar.gz" || { rm -rf "$_tmp"; die "could not download dumbpipe. Check the internet connection and run this again."; }
  _got=$(sha256_file "$_tgz")
  [ "$_got" = "$_sum" ] || { rm -rf "$_tmp"; die "dumbpipe download has the wrong SHA-256 ($_got); not installing it."; }
  mkdir -p "$_tmp/x"
  tar -xzf "$_tgz" -C "$_tmp/x" || { rm -rf "$_tmp"; die "could not unpack dumbpipe."; }
  _bin=$(find "$_tmp/x" -type f -name dumbpipe | head -n 1)
  [ -n "$_bin" ] || { rm -rf "$_tmp"; die "the dumbpipe download has no dumbpipe in it."; }
  mv -f "$_bin" "$DP" && chmod 755 "$DP"
  rm -rf "$_tmp"
}

make_secret() {
  # the machine's iroh identity: 32 random bytes as 64 hex, readable only by this user.
  # Kept across re-runs, so the endpoint id (and the registry entry) stays the same.
  _s=$A2K_HOME/iroh.secret
  if [ ! -s "$_s" ]; then
    ( umask 077; od -An -tx1 -N32 /dev/urandom | tr -d ' \n' > "$_s" )
  fi
  chmod 600 "$_s"
  [ "$(wc -c < "$_s" | tr -d ' ')" = 64 ] || die "could not make the machine key ($_s)."
}

# supporters' keys: "<key> a2k-op:<name>", one line each. Every other line stays exactly as it was.
write_keys() {
  mkdir -p "$SSH_HOME/.ssh" && chmod 700 "$SSH_HOME/.ssh"
  _ak=$AK
  [ -f "$_ak" ] || ( umask 077; : > "$_ak" )
  _ops=$(op_list)
  _new=$_ak.a2k-new
  grep -v ' a2k-op:[A-Za-z0-9._-]*[[:space:]]*$' "$_ak" > "$_new" || true
  printf '%s\n' "$_ops" | while read -r _n _k; do
    [ -n "$_n" ] && [ -n "$_k" ] && printf '%s a2k-op:%s\n' "$_k" "$_n"
  done >> "$_new"
  chmod 600 "$_new" && mv -f "$_new" "$_ak"
  OP_NAMES=$(printf '%s\n' "$_ops" | awk 'NF >= 2 { printf "%s%s", (n++ ? ", " : ""), $1 }')
}

service_kind() { cat "$A2K_HOME/service" 2>/dev/null || printf 'none'; }

# ---------------------------------------------------------------- Claude Code
want_claude() { case ",${A2K_LITE_SKIP:-}," in *,claude,*) return 1 ;; esac; return 0; }
claude_bin() {
  command -v claude 2>/dev/null && return 0
  for _c in "$HOME/.local/bin/claude" "$SSH_HOME/.local/bin/claude"; do [ -x "$_c" ] && { printf '%s' "$_c"; return 0; }; done
  return 1
}
# up to 3 minutes: the first start of a 180 MB program on a slow phone (or under CPU emulation) is slow
claude_version() { _cb=$(claude_bin) && with_timeout 180 "$_cb" --version 2>/dev/null | head -n 1 | tr -d '\r'; }
# Android: Anthropic publishes Claude Code only as native builds for regular Linux (glibc or musl),
# macOS and Windows; none runs on Android's own libc. Termux's glibc layer (glibc-repo, glibc-runner)
# can run the regular Linux build:
#   1. the current Linux build, its program loader pointed at Termux's glibc (patchelf), run directly
#   2. the same build started through grun (glibc-runner's launcher)
#   3. otherwise the last npm version that is plain JavaScript (2.1.112, April 2026) on Termux's Node.js
# The first that answers `claude --version` is kept. Updates by itself are off (they would fetch a build
# for regular Linux); `a2k-lite update-claude` installs the current one again.
CLAUDE_JS_LAST=2.1.112
android_claude() {
  _cl=$1
  _p=${PREFIX:-/data/data/com.termux/files/usr}
  _cd=$HOME/.local/share/a2k-claude          # outside the kit folder: uninstall never removes Claude Code
  _w=$_p/bin/claude
  pkg install -y nodejs-lts ripgrep > "$_cl" 2>&1 || { CLAUDE_STATE="failed: pkg install nodejs-lts ripgrep (see $_cl)"; return 1; }
  grep -q 'USE_BUILTIN_RIPGREP' "$HOME/.bashrc" 2>/dev/null || \
    printf '\n# a2k-lite: Claude Code uses Termux ripgrep (its own build does not run on Android)\nexport USE_BUILTIN_RIPGREP=0\n' >> "$HOME/.bashrc"
  export USE_BUILTIN_RIPGREP=0
  case $ARCH in aarch64) _np=linux-arm64 ;; x86_64) _np=linux-x64 ;; *) _np='' ;; esac
  _how=''
  # A2K_LITE_CLAUDE_JS=1 goes straight to route 3 (used by CI to test that route)
  if [ -n "$_np" ] && [ "${A2K_LITE_CLAUDE_JS:-}" != 1 ]; then
    { pkg install -y glibc-repo && pkg install -y glibc-runner patchelf; } >> "$_cl" 2>&1
    _ver=$(npm view @anthropic-ai/claude-code version 2>>"$_cl")
    _ld=$(ls "$_p"/glibc/lib/ld-linux-*.so* 2>/dev/null | head -n 1)
    if [ -n "$_ver" ] && [ -n "$_ld" ]; then
      _tmp=$(mktemp -d)
      if ( cd "$_tmp" && npm pack "@anthropic-ai/claude-code-$_np@$_ver" >> "$_cl" 2>&1 && tar -xzf ./*.tgz ) && [ -f "$_tmp/package/claude" ]; then
        mkdir -p "$_cd"; rm -f "$_cd"/claude-*
        # 1. patched copy
        cp "$_tmp/package/claude" "$_cd/claude-$_ver" && chmod 755 "$_cd/claude-$_ver"
        if patchelf --set-interpreter "$_ld" --set-rpath "$_p/glibc/lib" "$_cd/claude-$_ver" >> "$_cl" 2>&1; then
          printf '%s\n' "#!$_p/bin/sh" '# a2k-lite: Claude Code (Linux build, loader patched to Termux glibc)' \
            'unset LD_PRELOAD' 'export DISABLE_AUTOUPDATER=1 USE_BUILTIN_RIPGREP=0' "exec $_cd/claude-$_ver \"\$@\"" > "$_w"
          chmod 755 "$_w"
          [ -n "$(with_timeout 180 "$_w" --version 2>>"$_cl" | head -n 1)" ] && _how="Linux build $_ver on Termux glibc (patched loader)"
        fi
        # 2. grun
        if [ -z "$_how" ] && have grun; then
          cp -f "$_tmp/package/claude" "$_cd/claude-$_ver" && chmod 755 "$_cd/claude-$_ver"
          printf '%s\n' "#!$_p/bin/sh" '# a2k-lite: Claude Code (Linux build through grun)' \
            'unset LD_PRELOAD' 'export DISABLE_AUTOUPDATER=1 USE_BUILTIN_RIPGREP=0' "exec grun $_cd/claude-$_ver \"\$@\"" > "$_w"
          chmod 755 "$_w"
          [ -n "$(with_timeout 180 "$_w" --version 2>>"$_cl" | head -n 1)" ] && _how="Linux build $_ver on Termux glibc (grun)"
        fi
        [ -z "$_how" ] && { rm -f "$_w"; rm -rf "$_cd"; }
      fi
      rm -rf "$_tmp"
    fi
  fi
  # 3. plain JavaScript
  if [ -z "$_how" ]; then
    npm install -g "@anthropic-ai/claude-code@$CLAUDE_JS_LAST" >> "$_cl" 2>&1 || { CLAUDE_STATE="failed: npm install (see $_cl)"; return 1; }
    # npm's own `claude` starts with #!/usr/bin/env node, which Android does not have: start it with Termux's node
    _js=$(npm root -g 2>/dev/null)/@anthropic-ai/claude-code/cli.js
    # (npm's `claude` is a link to cli.js: remove the link first, or writing would overwrite cli.js itself)
    [ -f "$_js" ] && rm -f "$_w" && printf '%s\n' "#!$_p/bin/sh" "# a2k-lite: Claude Code $CLAUDE_JS_LAST (plain JavaScript) on Termux Node.js" \
      'export DISABLE_AUTOUPDATER=1 USE_BUILTIN_RIPGREP=0' "exec $_p/bin/node $_js \"\$@\"" > "$_w" && chmod 755 "$_w"
    grep -q 'DISABLE_AUTOUPDATER' "$HOME/.bashrc" 2>/dev/null || \
      printf '# a2k-lite: Claude Code %s is the last plain-JavaScript version; newer ones do not run on Android\nexport DISABLE_AUTOUPDATER=1\n' "$CLAUDE_JS_LAST" >> "$HOME/.bashrc"
    export DISABLE_AUTOUPDATER=1
    _how="npm $CLAUDE_JS_LAST (last plain-JavaScript version) on Termux Node.js"
  fi
  CLAUDE_HOW=$_how
  printf 'route: %s\n' "$_how" >> "$_cl"
  return 0
}

install_claude() {
  CLAUDE_OK=false
  if ! want_claude; then CLAUDE_STATE='left out (A2K_LITE_SKIP=claude)'; CLAUDE_OK=skip; return 0; fi
  if claude_bin >/dev/null && [ -n "$(claude_version)" ]; then CLAUDE_STATE="already installed: $(claude_version) (kept as it is)"; CLAUDE_OK=true; return 0; fi
  _cl=$A2K_HOME/claude-install.log
  case $OS in
    android)
      android_claude "$_cl" || return 1 ;;
    *)
      have bash || { CLAUDE_STATE='failed: the Claude Code installer needs bash'; return 1; }
      _ci=$A2K_HOME/claude-install.sh
      curl -fsSL -m 120 -o "$_ci" https://claude.ai/install.sh || { CLAUDE_STATE='failed: could not download the Claude Code installer'; return 1; }
      bash "$_ci" > "$_cl" 2>&1; _rc=$?
      rm -f "$_ci"
      [ $_rc = 0 ] || { CLAUDE_STATE="failed: the Claude Code installer exited $_rc (see $_cl)"; return 1; } ;;
  esac
  _v=$(claude_version)
  [ -n "$_v" ] || { CLAUDE_STATE="failed: installed but 'claude --version' does not answer (see $_cl)"; return 1; }
  CLAUDE_STATE="installed: $_v ($(claude_bin)${CLAUDE_HOW:+, $CLAUDE_HOW}); nobody is signed in"; CLAUDE_OK=true
}

# keep the settings this install was given (values are URLs, a key, a port, a name, a path: one line each)
write_config() {
  ( umask 077
    for _k in $SETTINGS; do
      eval "_v=\${$_k:-}"
      [ -n "$_v" ] && printf '%s=%s\n' "$_k" "$(printf '%s' "$_v" | tr -d '\n')"
    done > "$A2K_HOME/config" )
}
op_list() {
  if [ -n "${A2K_LITE_OPERATOR_KEYS_FILE:-}" ]; then cat "$A2K_LITE_OPERATOR_KEYS_FILE"; else printf '%s\n' "$OPERATOR_KEYS"; fi
}

install_service() {
  case $OS in
    linux)
      if have systemctl && [ -d /run/systemd/system ] && [ "$SUDO" != none ]; then
        _u=/etc/systemd/system/a2k-lite.service
        printf '%s\n' '[Unit]' 'Description=A2000 lite support kit (iroh tunnel to SSH)' 'After=network-online.target' 'Wants=network-online.target' '' \
          '[Service]' "User=$RUN_USER" "Environment=A2K_LITE_HOME=$A2K_HOME" "ExecStart=/bin/sh $SELF run" 'Restart=always' 'RestartSec=10' '' '[Install]' 'WantedBy=multi-user.target' \
          | $SUDO tee "$_u" >/dev/null
        $SUDO systemctl daemon-reload && $SUDO systemctl enable a2k-lite >/dev/null 2>&1
        printf 'systemd' > "$A2K_HOME/service"
      elif have systemctl && systemctl --user show-environment >/dev/null 2>&1; then
        mkdir -p "$HOME/.config/systemd/user"
        printf '%s\n' '[Unit]' 'Description=A2000 lite support kit (iroh tunnel to SSH)' '' '[Service]' "Environment=A2K_LITE_HOME=$A2K_HOME" "ExecStart=/bin/sh $SELF run" 'Restart=always' 'RestartSec=10' '' \
          '[Install]' 'WantedBy=default.target' > "$HOME/.config/systemd/user/a2k-lite.service"
        systemctl --user daemon-reload && systemctl --user enable a2k-lite >/dev/null 2>&1
        loginctl enable-linger "$RUN_USER" >/dev/null 2>&1 || warn "could not keep it running after you sign out (loginctl enable-linger needs an administrator)"
        printf 'systemd-user' > "$A2K_HOME/service"
      else
        # no systemd: start at boot from cron when there is one
        if have crontab; then
          ( crontab -l 2>/dev/null | grep -v 'a2k-lite start'; printf '@reboot A2K_LITE_HOME=%s /bin/sh %s start\n' "$A2K_HOME" "$SELF" ) | crontab - 2>/dev/null || warn "could not add the start-at-boot line to crontab"
        else warn "no systemd and no cron: the tunnel will not start by itself after a restart (run: a2k-lite start)"; fi
        printf 'background' > "$A2K_HOME/service"
      fi ;;
    macos)
      _plist_body() {
        printf '%s\n' '<?xml version="1.0" encoding="UTF-8"?>' \
          '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' \
          '<plist version="1.0"><dict>' '<key>Label</key><string>com.ai2000.a2k-lite</string>' \
          "<key>ProgramArguments</key><array><string>/bin/sh</string><string>$SELF</string><string>run</string></array>" \
          '<key>RunAtLoad</key><true/><key>KeepAlive</key><true/><key>ThrottleInterval</key><integer>10</integer>' \
          "<key>EnvironmentVariables</key><dict><key>HOME</key><string>$HOME</string><key>A2K_LITE_HOME</key><string>$A2K_HOME</string></dict>"
        [ "$1" = daemon ] && printf '<key>UserName</key><string>%s</string>\n' "$RUN_USER"
        printf '%s\n' '</dict></plist>'
      }
      if [ "$SUDO" != none ]; then
        _plist_body daemon | $SUDO tee /Library/LaunchDaemons/com.ai2000.a2k-lite.plist >/dev/null
        $SUDO chown root:wheel /Library/LaunchDaemons/com.ai2000.a2k-lite.plist; $SUDO chmod 644 /Library/LaunchDaemons/com.ai2000.a2k-lite.plist
        printf 'launchd' > "$A2K_HOME/service"
      else
        mkdir -p "$HOME/Library/LaunchAgents"
        _plist_body agent > "$HOME/Library/LaunchAgents/com.ai2000.a2k-lite.plist"
        printf 'launchd-user' > "$A2K_HOME/service"
      fi ;;
    android)
      # Termux:Boot (a free add-on app) runs ~/.termux/boot/* when the phone starts
      mkdir -p "$HOME/.termux/boot"
      printf '%s\n' "#!${PREFIX:-/data/data/com.termux/files/usr}/bin/sh" 'termux-wake-lock 2>/dev/null' 'sshd 2>/dev/null' "A2K_LITE_HOME='$A2K_HOME' exec sh $SELF start" > "$HOME/.termux/boot/a2k-lite"
      chmod 700 "$HOME/.termux/boot/a2k-lite"
      printf 'termux' > "$A2K_HOME/service" ;;
  esac
}

listener_pid() {
  _p=$(cat "$A2K_HOME/listener.pid" 2>/dev/null) || return 1
  [ -n "$_p" ] && kill -0 "$_p" 2>/dev/null && printf '%s' "$_p"
}

do_start() {
  case $(service_kind) in
    systemd) $SUDO systemctl restart a2k-lite ;;
    systemd-user) systemctl --user restart a2k-lite ;;
    launchd) $SUDO launchctl bootout system/com.ai2000.a2k-lite >/dev/null 2>&1; $SUDO launchctl bootstrap system /Library/LaunchDaemons/com.ai2000.a2k-lite.plist 2>/dev/null || $SUDO launchctl load -w /Library/LaunchDaemons/com.ai2000.a2k-lite.plist ;;
    launchd-user) launchctl bootout "gui/$(id -u)/com.ai2000.a2k-lite" >/dev/null 2>&1; launchctl bootstrap "gui/$(id -u)" "$HOME/Library/LaunchAgents/com.ai2000.a2k-lite.plist" 2>/dev/null || launchctl load -w "$HOME/Library/LaunchAgents/com.ai2000.a2k-lite.plist" ;;
    *)
      listener_pid >/dev/null && return 0
      [ $OS = android ] && have termux-wake-lock && termux-wake-lock 2>/dev/null
      nohup sh "$SELF" run >/dev/null 2>&1 &
      ;;
  esac
}

do_stop() {
  case $(service_kind) in
    systemd) $SUDO systemctl stop a2k-lite 2>/dev/null ;;
    systemd-user) systemctl --user stop a2k-lite 2>/dev/null ;;
    launchd) $SUDO launchctl bootout system/com.ai2000.a2k-lite 2>/dev/null || $SUDO launchctl unload /Library/LaunchDaemons/com.ai2000.a2k-lite.plist 2>/dev/null ;;
    launchd-user) launchctl bootout "gui/$(id -u)/com.ai2000.a2k-lite" 2>/dev/null || launchctl unload "$HOME/Library/LaunchAgents/com.ai2000.a2k-lite.plist" 2>/dev/null ;;
  esac
  _p=$(listener_pid) && kill "$_p" 2>/dev/null
  i=0; while [ $i -lt 10 ] && listener_pid >/dev/null; do sleep 1; i=$((i + 1)); done
  rm -f "$A2K_HOME/listener.pid"
}

# wait until the running tunnel has written this run's ticket
wait_ticket() {
  i=0
  while [ $i -lt "${1:-60}" ]; do
    [ -s "$A2K_HOME/ticket.txt" ] && listener_pid >/dev/null && return 0
    sleep 1; i=$((i + 1))
  done
  return 1
}

# ---------------------------------------------------------------- the tunnel (foreground; the service runs this)
cmd_run() {
  [ -x "$DP" ] || die "dumbpipe is missing ($DP). Run the install again."
  mkdir -p "$A2K_HOME"
  rm -f "$A2K_HOME/ticket.txt"
  IROH_SECRET=$(cat "$A2K_HOME/iroh.secret") || die "no machine key"
  export IROH_SECRET
  "$DP" listen-tcp --host "127.0.0.1:$SSH_PORT" > "$LOG.out" 2> "$LOG" &
  _dp=$!
  unset IROH_SECRET
  printf '%s' "$_dp" > "$A2K_HOME/listener.pid"
  trap 'kill $_dp 2>/dev/null; rm -f "$A2K_HOME/listener.pid"; exit 0' TERM INT HUP
  i=0
  while [ $i -lt 90 ] && kill -0 $_dp 2>/dev/null; do
    _t=$(cat "$LOG" "$LOG.out" 2>/dev/null | grep -o 'endpoint[a-z2-7]\{40,\}' | head -1)
    if [ -n "$_t" ]; then
      ( umask 077; printf '%s' "$_t" > "$A2K_HOME/ticket.txt" )
      # registered by itself whenever the ticket changes (after the install has done the first one)
      if [ -f "$A2K_HOME/installed" ] && [ "$_t" != "$(cat "$A2K_HOME/registered.ticket" 2>/dev/null)" ] && [ "${A2K_LITE_NO_REGISTER:-}" != 1 ]; then
        ( register quiet >> "$A2K_HOME/register.log" 2>&1 ) &
      fi
      break
    fi
    sleep 1; i=$((i + 1))
  done
  wait $_dp
  _rc=$?
  rm -f "$A2K_HOME/listener.pid"
  exit $_rc
}

# ---------------------------------------------------------------- self-test: dial our own ticket, sign in with a throwaway key
selftest() {
  SELFTEST='not run'
  _t=$(cat "$A2K_HOME/ticket.txt" 2>/dev/null)
  [ -n "$_t" ] || { SELFTEST='fail: no ticket'; return; }
  _d=$A2K_HOME/selftest; rm -rf "$_d"; mkdir -p "$_d"; chmod 700 "$_d"
  _tag="a2k-selftest-$(od -An -tx1 -N4 /dev/urandom | tr -d ' \n')"
  ssh-keygen -q -t ed25519 -N '' -C "$_tag" -f "$_d/id" >/dev/null 2>&1 || { SELFTEST='fail: ssh-keygen'; rm -rf "$_d"; return; }
  _ak=$AK
  cat "$_d/id.pub" >> "$_ak"
  _got=''
  # a fresh dialler for every try: right after a restart a dialler can stay stuck on the tunnel's old
  # connection (seen in CI), and a new one finds the new one
  for _try in 1 2 3 4 5 6; do
    _port=$(rand_port)
    "$DP" connect-tcp --addr "127.0.0.1:$_port" "$_t" > "$_d/dial.out" 2> "$_d/dial.err" &
    _dial=$!
    sleep 3
    _got=$(with_timeout 25 ssh -n -T -o BatchMode=yes -o ConnectTimeout=20 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \
      -o LogLevel=ERROR -i "$_d/id" -p "$_port" "$RUN_USER@127.0.0.1" "echo $_tag" 2>"$_d/ssh.err" | tr -d '\r')
    kill $_dial 2>/dev/null; wait $_dial 2>/dev/null
    [ "$_got" = "$_tag" ] && break
    sleep $_try
  done
  if [ "$_got" = "$_tag" ]; then SELFTEST="pass (ssh over its own ticket answered, try $_try)"
  else SELFTEST="fail: no ssh answer over the ticket in 6 tries ($(tail -n 1 "$_d/ssh.err" 2>/dev/null | tr -d '\r' | cut -c1-120))"; fi
  # remove ONLY the throwaway key line (by its unique comment)
  grep -v "$_tag" "$_ak" > "$_ak.a2k-new"; chmod 600 "$_ak.a2k-new"; mv -f "$_ak.a2k-new" "$_ak"
  rm -rf "$_d"
}

# ---------------------------------------------------------------- registration
post_json() {
  # $1 url  $2 body file  $3 response file  [$4 = gzip]  -> prints the HTTP code
  if [ "${4:-}" = gzip ]; then
    gzip -c "$2" | curl -sS -m 30 -o "$3" -w '%{http_code}' -X POST -H 'Content-Type: application/json' -H 'Content-Encoding: gzip' \
      -H "X-A2K-Key: $ENROLL_KEY" --data-binary @- "$1" 2>/dev/null
  else
    curl -sS -m 30 -o "$3" -w '%{http_code}' -X POST -H 'Content-Type: application/json' -H "X-A2K-Key: $ENROLL_KEY" --data-binary @"$2" "$1" 2>/dev/null
  fi
}

register() {
  _quiet=${1:-}
  _t=$(cat "$A2K_HOME/ticket.txt" 2>/dev/null)
  [ -n "$_t" ] || { REG_RESULT='not sent: no ticket yet (is the tunnel running?)'; [ -z "$_quiet" ] && say "  $REG_RESULT"; return 1; }
  _ep=$(endpoint_from_ticket "$_t") || { REG_RESULT='not sent: the ticket could not be read'; return 1; }
  printf '%s' "$_ep" > "$A2K_HOME/endpoint.txt"
  _dev=$(device_id); _host=$(host_name); _ts=$(now_iso)
  _w=$A2K_HOME/reg; rm -rf "$_w"; mkdir -p "$_w"; chmod 700 "$_w"

  # 1. the visit registry: this machine shows in /visits/devices (add-only on the server)
  printf '{"endpoint_id":"%s","host":%s,"device_id":"%s"}' "$_ep" "$(json_str "$_host")" "$_dev" > "$_w/enroll.json"
  _c=''; _r1=''
  for _try in 1 2 3; do
    _c=$(post_json "$REGISTRY_URL/visits/agent-enroll" "$_w/enroll.json" "$_w/enroll.out")
    if grep -q '"ok":true' "$_w/enroll.out" 2>/dev/null; then
      _nm=$(sed -n 's/.*"name":"\([^"]*\)".*/\1/p' "$_w/enroll.out")
      if grep -q '"already":true' "$_w/enroll.out"; then _r1="ok ($_nm, already listed)"; else _r1="ok ($_nm)"; fi
      break
    fi
    _r1="refused (HTTP ${_c:-none}: $(sed -n 's/.*"error":"\([^"]*\)".*/\1/p' "$_w/enroll.out" 2>/dev/null))"
    case $_c in 400|401|404|429) break ;; esac
    sleep $((3 * _try))
  done

  # 2. the enrollment inbox: the connect details (same envelope as the Windows kit; a2k_enroll.py reads it)
  _ok=$(selftest_ok)
  {
    printf '{"schema":"a2k-enroll/1","kit":"a2k-lite","kit_version":"%s","device_id":"%s","hostname":%s,"username":%s,' "$VERSION" "$_dev" "$(json_str "$_host")" "$(json_str "$RUN_USER")"
    printf '"os":%s,"ts":"%s",' "$(json_str "$(os_name)")" "$_ts"
    printf '"iroh":{"ticket":"%s","endpoint_id":"%s","ssh_user":%s,"ssh_port":%s,"running":%s,"selftest":%s,"dial":%s},' \
      "$_t" "$_ep" "$(json_str "$RUN_USER")" "$SSH_PORT" "$(listener_pid >/dev/null && printf true || printf false)" "$(json_str "${SELFTEST:-$(cat "$A2K_HOME/selftest.txt" 2>/dev/null)}")" \
      "$(json_str "dumbpipe connect-tcp --addr 127.0.0.1:12250 <ticket>  ;  ssh -p 12250 $RUN_USER@127.0.0.1")"
    _cs=${CLAUDE_STATE:-$(cat "$A2K_HOME/claude.txt" 2>/dev/null)}
    case $_cs in installed*|already*) _cok=true ;; *) _cok=false ;; esac
    printf '"components":{"iroh":{"ok":%s,"info":%s}' "$_ok" "$(json_str "dumbpipe $DUMBPIPE_VERSION, ssh port $SSH_PORT")"
    case $_cs in left*) ;; *) printf ',"claude":{"ok":%s,"info":%s}' "$_cok" "$(json_str "$_cs")" ;; esac
    printf '},"relay_registry":%s}' "$(json_str "$_r1")"
  } > "$_w/enrollment.json"
  ( umask 077; cp "$_w/enrollment.json" "$A2K_HOME/enrollment.json" )
  _b64=$(base64 < "$_w/enrollment.json" | tr -d '\r\n')
  printf '{"v":1,"runName":"enroll-%s-%s","uploadedAt":"%s","bugCount":0,"files":{"enrollment.json":"%s"}}' "$_host" "$(date -u +%s)" "$_ts" "$_b64" > "$_w/envelope.json"
  _r2=''
  for _try in 1 2 3; do
    _c=$(post_json "$INGEST_URL" "$_w/envelope.json" "$_w/ingest.out" gzip)
    if grep -q '"ok":true' "$_w/ingest.out" 2>/dev/null; then _r2=ok; break; fi
    _r2="refused (HTTP ${_c:-none})"
    case $_c in 400|401|413) break ;; esac
    sleep $((3 * _try))
  done
  rm -rf "$_w"

  REG_RESULT="registry: $_r1; connect details: $_r2"
  printf '%s %s\n' "$_ts" "$REG_RESULT" > "$A2K_HOME/registered.txt"
  [ -z "$_quiet" ] && { say "  visit registry:  $_r1"; say "  connect details: $_r2"; }
  case "$_r1/$_r2" in ok*/ok) ( umask 077; printf '%s' "$_t" > "$A2K_HOME/registered.ticket" ); return 0 ;; esac
  return 1
}
selftest_ok() { case "${SELFTEST:-$(cat "$A2K_HOME/selftest.txt" 2>/dev/null)}" in pass*) printf true ;; *) printf false ;; esac; }

# ---------------------------------------------------------------- commands
cmd_install() {
  detect_platform
  say ''
  say '  A2000 LITE SUPPORT KIT (command line, no screen)'
  say '  ------------------------------------------------'
  say "  This machine: $(os_name), user $RUN_USER"
  if [ $OS = android ]; then
    _rel=$(getprop ro.build.version.release 2>/dev/null | cut -d. -f1)
    case $_rel in [0-6]) die "Android $_rel is too old for Termux (it needs Android 7 or later)." ;; esac
  fi
  _sshnow=no; ssh_answers "$SSH_PORT" && _sshnow=yes
  say '  It will:'
  if [ $_sshnow = yes ]; then
    if [ $OS = android ]; then say "    1. keep the SSH server that already answers on port $SSH_PORT$(penalties_apply && printf '; one setting: sign-in failures through the tunnel do not shut out every supporter')"
    else say "    1. keep the SSH server that already answers on port $SSH_PORT (nothing changed in it)"
      penalties_apply && say "       note: this OpenSSH shuts out an address after failed sign-ins, and all supporters arrive from 127.0.0.1. An administrator can add '$EXEMPT_LINE' to its settings."
    fi
  else case $OS in
    linux) say "    1. install and start an OpenSSH server (about 5 MB$( [ "$SUDO" = sudo ] && printf '; asks for your password through sudo'))" ;;
    macos) say "    1. turn on Remote Login (the SSH server built into macOS$( [ "$SUDO" = sudo ] && printf '; asks for your password through sudo'))" ;;
    android) say '    1. install the Termux OpenSSH server (about 5 MB), port 8022' ;;
  esac; fi
  say "    2. install dumbpipe $DUMBPIPE_VERSION (an iroh tunnel, about 8 MB) in $A2K_HOME, always on, starts at boot"
  say "    3. let these GCS supporters sign in with their SSH key: $(op_list | awk 'NF >= 2 { printf "%s%s", (n++ ? ", " : ""), $1 }')"
  if want_claude; then
    if claude_bin >/dev/null; then say '    4. keep the Claude Code that is already here'
    elif [ $OS = android ]; then say '    4. install Claude Code (Node.js + ripgrep from Termux, then npm; about 250 MB). Nobody is signed in'
    else say "    4. install Claude Code with Anthropic's installer (about 200 MB, in ~/.local). Nobody is signed in"; fi
  else say '    4. (Claude Code left out: A2K_LITE_SKIP=claude)'; fi
  say '    5. register this machine with GCS support (its name, device id and connect ticket)'
  say '  Nothing else: no screen sharing, no recorder. Remove it any time: a2k-lite uninstall (Claude Code and SSH stay)'
  [ $OS = android ] && say '  On Android: install Termux:Boot (F-Droid) and open it once so the tunnel starts with the phone; turn off battery optimisation for Termux.'
  _free=$(df -Pk "$HOME" 2>/dev/null | awk 'NR == 2 { print int($4 / 1024) }')
  _need=30; want_claude && ! claude_bin >/dev/null && _need=300
  [ -n "$_free" ] && [ "$_free" -lt $_need ] && die "only $_free MB free in $HOME; the kit needs about $_need MB."
  curl -s -m 10 -o /dev/null "$REGISTRY_URL/visits/health" || die "cannot reach $REGISTRY_URL (no internet?). Nothing was changed."
  if [ "${A2K_LITE_YES:-}" != 1 ]; then
    [ -r /dev/tty ] || die "no keyboard to answer the question. Run it again with A2K_LITE_YES=1 to agree without a question."
    printf '\n  Type YES to install: '
    read -r _ans < /dev/tty || _ans=''
    [ "$_ans" = YES ] || die "not installed (you typed '$_ans')."
  fi
  say ''
  need_tools
  say '  [1/6] SSH server';   ensure_sshd; say "        $SSHD_STATE"
  say '  [2/6] dumbpipe';     install_dumbpipe; make_secret
  mkdir -p "$A2K_HOME/bin"; chmod 700 "$A2K_HOME"
  _me=$0; case $_me in */*) ;; *) _me=$(command -v "$_me" 2>/dev/null || printf '%s' "$_me") ;; esac
  if [ -f "$_me" ] && ! [ "$_me" -ef "$SELF" ]; then cp -f "$_me" "$SELF"; elif [ ! -f "$SELF" ]; then
    die "run the kit from a file (curl -fsSL <url> -o a2k-lite.sh && sh a2k-lite.sh install), not through a pipe"; fi
  # Termux has no /bin/sh: its copy starts with Termux's own shell
  [ $OS = android ] && sed "1s|.*|#!${PREFIX:-/data/data/com.termux/files/usr}/bin/sh|" "$SELF" > "$SELF.new" && mv -f "$SELF.new" "$SELF"
  chmod 755 "$SELF"
  write_config
  mkdir -p "$(dirname "$BIN_LINK")" && ln -sf "$SELF" "$BIN_LINK"
  _dev=$(device_id); printf '{"device_id":"%s","host":%s}\n' "$_dev" "$(json_str "$(host_name)")" > "$A2K_HOME/device.json"
  say "        $DP"
  say '  [3/6] supporter keys'; write_keys; say "        $AK: $OP_NAMES"
  say '  [4/6] tunnel'
  rm -f "$A2K_HOME/installed"
  do_stop; install_service; do_start
  wait_ticket 60 || die "the tunnel did not start. Last lines of $LOG:
$(tail -n 5 "$LOG" 2>/dev/null)"
  say "        running ($(service_kind)); endpoint $(endpoint_from_ticket "$(cat "$A2K_HOME/ticket.txt")")"
  selftest; printf '%s' "$SELFTEST" > "$A2K_HOME/selftest.txt"
  say "        self-test: $SELFTEST"
  say '  [5/6] Claude Code'; install_claude; say "        $CLAUDE_STATE"
  printf '%s' "$CLAUDE_STATE" > "$A2K_HOME/claude.txt"
  say '  [6/6] registering with GCS support'
  if [ "${A2K_LITE_NO_REGISTER:-}" = 1 ]; then say '        A2K_LITE_NO_REGISTER=1: not sent'; _reg=1
  else register; _reg=$?; fi
  : > "$A2K_HOME/installed"
  say ''
  if [ $_reg = 0 ]; then say "  Done. $(host_name) ($_dev) is registered; GCS support can now open a visit to it."
  else
    say '  Installed, but the registration did not go through. Send GCS support the line below:'
    say "    host $(host_name)  device $_dev  ssh user $RUN_USER  port $SSH_PORT"
    say '    ticket: run  a2k-lite ticket  and send what it prints'
  fi
  case ":$PATH:" in *":$(dirname "$BIN_LINK"):"*) ;; *) say "  (the command is $BIN_LINK; add $(dirname "$BIN_LINK") to PATH to type just a2k-lite)" ;; esac
  case $SELFTEST in pass*) ;; *) return 2 ;; esac
  [ $_reg = 0 ] || return 3
  [ "$CLAUDE_OK" = false ] && return 4
  return 0
}

cmd_status() {
  detect_platform
  [ -d "$A2K_HOME" ] || { say '  a2k-lite is not installed here.'; return 1; }
  _p=$(listener_pid); _rc=0
  say "  kit:        a2k-lite $VERSION, dumbpipe $DUMBPIPE_VERSION, start at boot: $(service_kind)"
  say "  machine:    $(host_name)  $(device_id)  $(os_name)"
  if [ -n "$_p" ]; then say "  tunnel:     running (pid $_p)"; else say '  tunnel:     NOT running (a2k-lite start)'; _rc=1; fi
  if ssh_answers "$SSH_PORT"; then say "  ssh:        answering on port $SSH_PORT (user $RUN_USER)"; else say "  ssh:        NOT answering on port $SSH_PORT"; _rc=1; fi
  [ -s "$A2K_HOME/endpoint.txt" ] && say "  endpoint:   $(cat "$A2K_HOME/endpoint.txt")"
  [ -s "$A2K_HOME/ticket.txt" ] && say '  ticket:     saved (a2k-lite ticket prints it)'
  say "  self-test:  $(cat "$A2K_HOME/selftest.txt" 2>/dev/null || printf 'not run')"
  if want_claude; then _v=$(claude_version); say "  claude:     ${_v:-not answering}"; fi
  say "  registered: $(cat "$A2K_HOME/registered.txt" 2>/dev/null || printf 'not yet')"
  say "  supporters: $(grep -o ' a2k-op:[A-Za-z0-9._-]*' "$AK" 2>/dev/null | sed 's/ a2k-op://' | tr '\n' ' ')"
  return $_rc
}

cmd_uninstall() {
  detect_platform
  [ -d "$A2K_HOME" ] || { say '  a2k-lite is not installed here.'; return 0; }
  if [ "${A2K_LITE_YES:-}" != 1 ] && [ -r /dev/tty ]; then
    printf '  Remove the A2000 lite support kit (the SSH server stays as it is)? Type YES: '
    read -r _ans < /dev/tty || _ans=''; [ "$_ans" = YES ] || die 'nothing removed.'
  fi
  do_stop
  case $(service_kind) in
    systemd) $SUDO systemctl disable a2k-lite >/dev/null 2>&1; $SUDO rm -f /etc/systemd/system/a2k-lite.service; $SUDO systemctl daemon-reload ;;
    systemd-user) systemctl --user disable a2k-lite >/dev/null 2>&1; rm -f "$HOME/.config/systemd/user/a2k-lite.service"; systemctl --user daemon-reload ;;
    launchd) $SUDO rm -f /Library/LaunchDaemons/com.ai2000.a2k-lite.plist ;;
    launchd-user) rm -f "$HOME/Library/LaunchAgents/com.ai2000.a2k-lite.plist" ;;
    termux) rm -f "$HOME/.termux/boot/a2k-lite" ;;
    background) have crontab && crontab -l 2>/dev/null | grep -v 'a2k-lite start' | crontab - 2>/dev/null ;;
  esac
  # the loopback setting this kit added (sshd keeps running; it reads it at its next start)
  [ -f /etc/ssh/sshd_config.d/a2k-lite.conf ] && [ "$SUDO" != none ] && $SUDO rm -f /etc/ssh/sshd_config.d/a2k-lite.conf
  if [ $OS = android ]; then
    _cf=${PREFIX:-/data/data/com.termux/files/usr}/etc/ssh/sshd_config
    grep -q '^# a2k-lite: supporters' "$_cf" 2>/dev/null && { grep -v -e '^# a2k-lite: supporters' -e "^$EXEMPT_LINE\$" "$_cf" > "$_cf.a2k-new" && mv -f "$_cf.a2k-new" "$_cf"; }
  fi
  # only the kit's own key lines; the person's keys stay. The SSH server is never removed or turned off.
  _ak=$AK
  if [ -f "$_ak" ]; then
    grep -v -e ' a2k-op:[A-Za-z0-9._-]*[[:space:]]*$' -e 'a2k-selftest-' "$_ak" > "$_ak.a2k-new"; chmod 600 "$_ak.a2k-new"; mv -f "$_ak.a2k-new" "$_ak"
  fi
  [ "$(readlink "$BIN_LINK" 2>/dev/null)" = "$SELF" ] && rm -f "$BIN_LINK"
  rm -rf "$A2K_HOME"
  say '  Removed: the tunnel, its start-at-boot entry, the supporter key lines and the kit folder.'
  say '  Kept: the SSH server and Claude Code (they may be used for other things), and the registry record (GCS support removes'
  say '  it from the relay list with relay-allow.sh).'
}

main() {
  _c=${1:-help}; [ $# -gt 0 ] && shift
  case $_c in
    install) cmd_install "$@" ;;
    run) detect_platform; cmd_run ;;
    start) detect_platform; do_start; wait_ticket 60 && say '  running' || { say "  did not start (see $LOG)"; exit 1; } ;;
    stop) detect_platform; do_stop; say '  stopped' ;;
    restart) detect_platform; do_stop; do_start; wait_ticket 60 && say '  running' || { say "  did not start (see $LOG)"; exit 1; } ;;
    status) cmd_status ;;
    register) detect_platform; register ;;
    ticket) detect_platform; cat "$A2K_HOME/ticket.txt" 2>/dev/null && printf '\n' || { say '  no ticket (is the tunnel running?)'; exit 1; } ;;
    endpoint-from-ticket) endpoint_from_ticket "${1:-}" ;;
    uninstall) cmd_uninstall ;;
    update-claude) detect_platform; mkdir -p "$A2K_HOME"
      if [ $OS = android ]; then rm -f "${PREFIX:-/data/data/com.termux/files/usr}/bin/claude"; npm uninstall -g @anthropic-ai/claude-code >/dev/null 2>&1; fi
      if [ $OS = android ]; then CLAUDE_HOW=''; android_claude "$A2K_HOME/claude-install.log" && say "  $(claude_version) ($CLAUDE_HOW)" || { say "  $CLAUDE_STATE"; exit 1; }
      else _cb=$(claude_bin) && "$_cb" update || install_claude; fi ;;
    version|--version) say "a2k-lite $VERSION (dumbpipe $DUMBPIPE_VERSION)" ;;
    help|-h|--help) sed -n '2,30p' "$0" | sed 's/^# \{0,1\}//' ;;
    *) die "unknown command '$_c' (a2k-lite help)" ;;
  esac
}
main "$@"
