#!/usr/bin/env bash
# safeaictl: run and look after SafeAI Edge on this server. Run as root (sudo).
set -euo pipefail
ENVF=/etc/safeai/safeai.env
[ -f "$ENVF" ] || { echo "SafeAI is not installed here ($ENVF missing)."; exit 1; }
# shellcheck disable=SC1090
. "$ENVF"
DATA=${DATA:-/var/lib/safeai}; NAME=safeai; IMG=safeai/observe; UIDGID="${SAFEAI_UID:-10001}:${SAFEAI_GID:-${SAFEAI_UID:-10001}}"
RELEASES=/opt/safeai/releases; KEY=/etc/safeai/release-key.pem

die() { echo "safeaictl: $*" >&2; exit 1; }
need_root() { [ "$(id -u)" = 0 ] || die "run this as root (sudo safeaictl $cmd)"; }
setenv() {   # only plain values: this file is read by the shell as root
  [[ "$1" =~ ^[A-Z_]+$ && "$2" =~ ^[A-Za-z0-9._:/,-]*$ ]] || die "refusing to write an unexpected value for $1"
  sed -i "s|^$1=.*|$1=$2|" "$ENVF"; grep -q "^$1=" "$ENVF" || echo "$1=$2" >> "$ENVF"; }
newer() { [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -1)" = "$1" ] && [ "$1" != "$2" ]; }   # is $1 newer than $2
host_ips() { if [ "${HOST_IPS:-auto}" = auto ]; then ip -4 -o addr show scope global 2>/dev/null | awk '$2 !~ /^(docker|br-|veth)/ {split($4, a, "/"); print a[1]}' | paste -sd, -; else echo "$HOST_IPS"; fi; }

run_container() {   # $1 = version
  docker rm -f "$NAME" >/dev/null 2>&1 || true
  if [ "${COLLECTOR:-0}" = 1 ]; then          # a site collector: no console and no listening ports; it connects out to the central SafeAI
    docker run -d --name "$NAME" --restart unless-stopped -v "$DATA:/var/lib/safeai" --user "$UIDGID" --read-only --tmpfs /tmp:rw,size=256m \
      --cap-drop ALL --security-opt no-new-privileges --memory "${MEMORY:-2g}" --pids-limit 512 --log-opt max-size=20m --log-opt max-file=5 \
      "$IMG:$1" collector run >/dev/null
    return
  fi
  docker run -d --name "$NAME" --restart unless-stopped \
    -p "${BIND:-0.0.0.0}:${HTTPS_PORT:-443}:8443" -p "${AGENT_BIND:-${BIND:-0.0.0.0}}:${AGENT_PORT:-8444}:8444" -p "${SYSLOG_BIND:-${BIND:-0.0.0.0}}:${SYSLOG_PORT:-514}:5514/udp" -p "${SYSLOG_BIND:-${BIND:-0.0.0.0}}:${SYSLOG_PORT:-514}:5514/tcp" -p "${FLOW_BIND:-${BIND:-0.0.0.0}}:${FLOW_PORT:-2055}:2055/udp" \
    -v "$DATA:/var/lib/safeai" --user "$UIDGID" --read-only --tmpfs /tmp:rw,size=256m --cap-drop ALL --security-opt no-new-privileges \
    --memory "${MEMORY:-2g}" --pids-limit 512 --log-opt max-size=20m --log-opt max-file=5 \
    -e SAFEAI_HOST_IPS="$(host_ips)" -e SAFEAI_SYSLOG_PUBLIC_PORT="${SYSLOG_PORT:-514}" -e SAFEAI_AGENT_PUBLIC_PORT="${AGENT_PORT:-8444}" \
    ${HTTPS_PROXY:+-e HTTPS_PROXY="$HTTPS_PROXY" -e NO_PROXY="${NO_PROXY:-localhost,127.0.0.1}"} "$IMG:$1" serve >/dev/null   # an outbound proxy for cloud APIs, when set in safeai.env
  clear_udp_paths
}

clear_udp_paths() {   # devices that kept sending syslog/flows while the container was replaced stay on a path without address
                      # translation for as long as they keep sending, and arrive from Docker's gateway; clear those so they take the new one
  command -v conntrack >/dev/null 2>&1 || return 0
  local p
  for p in "${SYSLOG_PORT:-514}" "${FLOW_PORT:-2055}"; do conntrack -D -p udp --dport "$p" >/dev/null 2>&1 || true; done
}

wait_healthy() {    # $1 = version, $2 = seconds
  local t=0
  if [ "${COLLECTOR:-0}" = 1 ]; then          # a collector has no web port: healthy = still running after a while
    sleep 8; [ "$(docker inspect -f '{{.State.Running}}' "$NAME" 2>/dev/null)" = true ] && [ "$(docker inspect -f '{{.Config.Image}}' "$NAME")" = "$IMG:$1" ]; return
  fi
  while [ "$t" -lt "$2" ]; do
    local v
    v=$(docker exec "$NAME" python -c "import ssl,json,urllib.request;print(json.load(urllib.request.urlopen('https://127.0.0.1:8443/healthz',context=ssl._create_unverified_context(),timeout=4))['version'])" 2>/dev/null || true)
    [ "$v" = "$1" ] && return 0
    sleep 3; t=$((t + 3))
  done
  return 1
}

free_mb() { df -Pm "$1" 2>/dev/null | awk 'NR==2 {print $4}'; }
docker_root() { docker info -f '{{.DockerRootDir}}' 2>/dev/null || echo /var/lib/docker; }

prune_releases() {   # keep the running version and the one 'rollback' returns to; remove every other release folder and image
  local keep1="$SAFEAI_VERSION" keep2="${SAFEAI_PREVIOUS:-}" n=0 v
  for d in "$RELEASES"/*/; do
    v=$(basename "$d"); [ -d "$d" ] || continue
    [ "$v" = "$keep1" ] || [ "$v" = "$keep2" ] && continue
    rm -rf "${RELEASES:?}/$v"; docker image rm "$IMG:$v" >/dev/null 2>&1 || true; n=$((n + 1))
  done
  for v in $(docker image ls "$IMG" --format '{{.Tag}}' 2>/dev/null); do   # images left by an upgrade that stopped half-way
    [ "$v" = "$keep1" ] || [ "$v" = "$keep2" ] || [ -d "$RELEASES/$v" ] || { docker image rm "$IMG:$v" >/dev/null 2>&1 || true; }
  done
  echo "Removed $n old release(s); kept $keep1${keep2:+ and $keep2 (for rollback)}."
}

verify_bundle() {   # $1 = extracted bundle dir; checks every file against SHA256SUMS and SHA256SUMS against the release key
  # nothing may be in the bundle that the signed list doesn't name, and nothing may be setuid/setgid or a link
  local extra
  extra=$(cd "$1" && find . -mindepth 1 \( -type f -o -type l \) ! -name SHA256SUMS ! -name SHA256SUMS.sig -printf '%P\n' | sort | comm -23 - <(awk '{print $2}' SHA256SUMS | sed 's|^\*||' | sort))
  [ -z "$extra" ] || die "the bundle contains files its signed list doesn't name: not installing it"
  [ -z "$(find "$1" \( -perm -4000 -o -perm -2000 -o -type l \) -print -quit)" ] || die "the bundle contains links or setuid files: not installing it"
  ( cd "$1" && sha256sum -c --quiet SHA256SUMS ) || die "checksum mismatch in $1: the bundle is damaged or was changed"
  [ -f "$KEY" ] || die "no release key at $KEY"
  openssl pkeyutl -verify -pubin -inkey "$KEY" -rawin -in "$1/SHA256SUMS" -sigfile "$1/SHA256SUMS.sig" >/dev/null 2>&1 \
    || die "the bundle's signature doesn't match SafeCadence's release key: not installing it"
}

backup_now() {      # prints the backup file name. Waits for SafeAI first (it may have just restarted, e.g. after a rollback) and tries 3 times.
  local out f i
  wait_healthy "$SAFEAI_VERSION" 120 >/dev/null 2>&1 || true
  for i in 1 2 3; do
    out=$(docker exec "$NAME" python -m safeai_observe backup "$@" 2>&1) || true      # the answer is the JSON line; log lines may come with it
    f=$(printf '%s\n' "$out" | python3 -c "
import json, sys
for l in reversed(sys.stdin.read().splitlines()):
    try: d = json.loads(l)
    except ValueError: continue
    if isinstance(d, dict) and d.get('file'): print(d['file']); break
" 2>/dev/null) && [ -n "$f" ] && { echo "$f"; return 0; }
    sleep 10
  done
  die "couldn't take a backup (SafeAI answered: $(printf '%s' "$out" | tail -c 200)); nothing was changed"
}

restore_file() {    # $1 = a backup file (a path, or the name of one in $DATA/backups); $2 = image version to run the restore with
  local f="$1" base
  docker stop "$NAME" >/dev/null 2>&1 || true      # nothing writes the data while it's replaced (the caller starts SafeAI again)
  if [ -f "$f" ] && [ ! -L "$f" ]; then           # the operator's own file, copied under a new unique name
    base="restore-$(date -u +%Y%m%dT%H%M%SZ)-$$.tar.gz"
    docker run --rm -i -v "$DATA:/var/lib/safeai" --user "$UIDGID" --read-only --cap-drop ALL --entrypoint python "$IMG:$2" -c \
      "import os,sys,shutil;os.makedirs('/var/lib/safeai/backups',exist_ok=True);shutil.copyfileobj(sys.stdin.buffer,open('/var/lib/safeai/backups/'+sys.argv[1],'xb'))" "$base" < "$f" \
      || die "couldn't copy $f into SafeAI's data"
  else
    base=$(basename "$f"); [[ "$base" =~ ^[A-Za-z0-9._-]+$ ]] || die "no such backup: $f"
    docker run --rm -v "$DATA:/var/lib/safeai" --user "$UIDGID" --read-only --entrypoint test "$IMG:$2" -f "/var/lib/safeai/backups/$base" || die "no such backup: $f"
  fi
  docker rm -f "$NAME" >/dev/null 2>&1 || true
  docker run --rm -v "$DATA:/var/lib/safeai" --user "$UIDGID" --read-only --tmpfs /tmp --cap-drop ALL --security-opt no-new-privileges "$IMG:$2" restore "/var/lib/safeai/backups/$base"
}

in_container() {    # run a SafeAI command inside the running container (the data never passes through root on the host)
  docker exec -i "$NAME" python -m safeai_observe "$@"
}

# ---------------------------------------------------------------- the helper (safeai-helper.timer runs 'safeaictl helper-tick' every minute)
# SafeAI runs in a locked-down container and can't stop itself, so the console's Backups page asks this helper, through two files in
# $DATA/state, to restore a backup (state/restore-request.json -> backups/.restore-result.json); the helper also copies new backups off this server
# (Settings, Backups: a folder such as a mounted file share, or another server over SSH) and says it's alive (host-helper.json).
COPYKEY=/etc/safeai/backup-copy_ed25519
BACKUP_RX='^(safeai-backup-[0-9]{8}T[0-9]{6}Z|upload-[0-9]{8}T[0-9]{6}Z|restore-[0-9]{8}T[0-9]{6}Z-[0-9]+)\.tar\.gz$'

state_write() {     # $1 = a file under $DATA (state/... or backups/...), stdin = its JSON; written as SafeAI's user so the console can read it
  local f="$DATA/$1" d tmp
  d=$(dirname "$f"); [ -d "$DATA" ] || return 0
  [ -d "$d" ] || { install -d -m 0750 "$d"; chown "$UIDGID" "$d"; }
  tmp=$(mktemp "$d/.helper.XXXXXX"); cat > "$tmp"; chown "$UIDGID" "$tmp"; chmod 600 "$tmp"; mv -f "$tmp" "$f"
}

helper_alive() {
  local pub=""; [ -f "$COPYKEY.pub" ] && pub=$(awk '{print $1" "$2}' "$COPYKEY.pub")
  PUB="$pub" VER="$SAFEAI_VERSION" python3 -c 'import json,os,time;print(json.dumps({"at":time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime()),"version":os.environ["VER"],"can_restore":True,"ssh_public_key":os.environ["PUB"]}))' \
    | state_write state/host-helper.json
}

helper_restore() {  # an owner asked for a restore in the console, within the last 10 minutes
  local req="$DATA/state/restore-request.json" file id by pre
  [ -f "$req" ] || return 0
  read -r id file by < <(python3 - "$req" <<'PY'
import json, re, sys, time, calendar
try: r = json.load(open(sys.argv[1]))
except Exception: print("bad - -"); sys.exit()
ok = re.fullmatch(r"(safeai-backup-\d{8}T\d{6}Z|upload-\d{8}T\d{6}Z|restore-\d{8}T\d{6}Z-\d+)\.tar\.gz", str(r.get("file", "")))
try: age = time.time() - calendar.timegm(time.strptime(str(r.get("t"))[:19], "%Y-%m-%dT%H:%M:%S"))
except ValueError: age = 1e9
idv = re.sub(r"[^0-9]", "", str(r.get("id", ""))) or "0"; by = re.sub(r"[^A-Za-z0-9._@-]", "", str(r.get("by", "")))[:60] or "-"
print(idv if ok and 0 <= age <= 600 else "expired", r.get("file") if ok else "-", by)
PY
)
  rm -f "$req"
  if [ "$id" = expired ] || [ "$id" = bad ]; then
    printf '{"state":"refused","error":"the request was older than 10 minutes or not valid; ask again","at":"%s"}\n' "$(date -u +%FT%TZ)" | state_write backups/.restore-result.json; return 0
  fi
  [ -f "$DATA/backups/$file" ] || { printf '{"id":"%s","state":"failed","file":"%s","error":"the backup file is gone","at":"%s"}\n' "$id" "$file" "$(date -u +%FT%TZ)" | state_write backups/.restore-result.json; return 0; }
  logger -t safeai "restore of $file asked for by $by in the console"
  pre=$(backup_now --kind=restore) || { printf '{"id":"%s","state":"failed","file":"%s","error":"could not take the backup before restoring; nothing was changed","at":"%s"}\n' "$id" "$file" "$(date -u +%FT%TZ)" | state_write backups/.restore-result.json; return 0; }
  if ( restore_file "$file" "$SAFEAI_VERSION" ) && run_container "$SAFEAI_VERSION" && wait_healthy "$SAFEAI_VERSION" 120; then
    printf '{"id":"%s","state":"done","file":"%s","by":"%s","before":"%s","at":"%s"}\n' "$id" "$file" "$by" "$pre" "$(date -u +%FT%TZ)" | state_write backups/.restore-result.json
    logger -t safeai "restored $file (the data before it is in $pre)"
  else
    run_container "$SAFEAI_VERSION" >/dev/null 2>&1 || true; wait_healthy "$SAFEAI_VERSION" 120 || true
    printf '{"id":"%s","state":"failed","file":"%s","before":"%s","error":"the restore did not finish; SafeAI was started again. The data from before is in %s","at":"%s"}\n' "$id" "$file" "$pre" "$pre" "$(date -u +%FT%TZ)" | state_write backups/.restore-result.json
  fi
}

helper_copy() {     # copy backups not copied yet to the destination set in the console; every 10 minutes at most, every 30 after a failure
  local cfgf="$DATA/config.json" st="$DATA/backups/.copy.json"
  [ -f "$cfgf" ] || return 0
  python3 - "$cfgf" "$st" "$DATA/backups" "$COPYKEY" <<'PY' | state_write backups/.copy.json
import json, os, re, shutil, subprocess, sys, time, calendar
cfgf, stf, bdir, key = sys.argv[1:5]
NAME = re.compile(r"(safeai-backup-\d{8}T\d{6}Z|upload-\d{8}T\d{6}Z|restore-\d{8}T\d{6}Z-\d+)\.tar\.gz")
now = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
try: st = json.load(open(stf))
except Exception: st = {}
def age(ts):
    try: return time.time() - calendar.timegm(time.strptime(str(ts)[:19], "%Y-%m-%dT%H:%M:%S"))
    except ValueError: return 1e9
try: cp = (json.load(open(cfgf)).get("backup") or {}).get("copy") or {}
except Exception: cp = {}
kind, target, keep = cp.get("kind", "off"), str(cp.get("target") or ""), cp.get("keep", 30)
def out(**kw):
    st.update(kw); st.update({"kind": kind, "target": target}); st["copied"] = st.get("copied", [])[-300:]; print(json.dumps(st)); sys.exit()
if kind not in ("folder", "ssh"): out(state="off")
if st.get("target") != target or st.get("kind") != kind: st = {"copied": []}             # a new destination: copy everything again
wait = 1800 if st.get("error") else 600
if age(st.get("last_try")) < wait: out()
files = sorted(f for f in os.listdir(bdir) if NAME.fullmatch(f))
todo = [f for f in files if f not in st.get("copied", [])]
st["last_try"] = now
if not todo: out(error=None, state="ok", last_ok=st.get("last_ok") or now)
try:
    if kind == "folder":
        if not re.fullmatch(r"/[A-Za-z0-9._/-]{1,200}", target) or ".." in target.split("/") or target.startswith(("/var/lib/safeai", "/etc", "/proc", "/sys", "/dev")) or target.rstrip("/") in ("", "/root", "/opt/safeai"):
            raise RuntimeError("the folder isn't allowed")
        if not os.path.isdir(target): raise RuntimeError(f"{target} doesn't exist on the server (is the file share mounted?)")
        for f in todo:
            tmp = os.path.join(target, "." + f + ".partial"); shutil.copyfile(os.path.join(bdir, f), tmp); os.chmod(tmp, 0o600); os.replace(tmp, os.path.join(target, f))
            st.setdefault("copied", []).append(f)
        have = sorted(f for f in os.listdir(target) if NAME.fullmatch(f) and f.startswith("safeai-backup-"))
        for f in have[:-int(keep)] if isinstance(keep, int) and keep > 0 else []:
            try: os.unlink(os.path.join(target, f))
            except OSError: pass
    else:
        if not re.fullmatch(r"[A-Za-z0-9._-]{1,64}@[A-Za-z0-9.-]{1,253}:[A-Za-z0-9._/~-]{1,200}", target): raise RuntimeError("the server address isn't allowed")
        if not os.path.exists(key): raise RuntimeError("no SSH key yet: run sudo safeaictl backup-copy-key on this server and add the key it prints to the backup server")
        ssh = f"ssh -i {key} -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/etc/safeai/backup-copy_known_hosts -o ConnectTimeout=20"
        r = subprocess.run(["rsync", "-a", "--chmod=F600", "--ignore-existing", "--partial", "-e", ssh] + [os.path.join(bdir, f) for f in todo] + [target.rstrip("/") + "/"],
                           capture_output=True, text=True, timeout=3600)
        if r.returncode: raise RuntimeError("rsync: " + (r.stderr.strip().splitlines() or ["failed"])[-1][:200])
        st.setdefault("copied", []).extend(todo)
    out(error=None, state="ok", last_ok=now, last_count=len(todo))
except Exception as e:
    out(error=str(e)[:300], state="failing")
PY
}

cmd=${1:-status}; shift || true
case "$cmd" in
  start)   need_root; run_container "$SAFEAI_VERSION"; wait_healthy "$SAFEAI_VERSION" 120 && echo "SafeAI $SAFEAI_VERSION is running." || die "started, but the console didn't answer within 2 minutes; see: safeaictl logs" ;;
  stop)    need_root; docker stop "$NAME" >/dev/null && echo stopped ;;
  restart) need_root; run_container "$SAFEAI_VERSION"     # recreated, so changes in safeai.env (BIND, ports) take effect
           wait_healthy "$SAFEAI_VERSION" 120 && echo restarted || die "SafeAI didn't answer within 2 minutes; see: safeaictl logs" ;;
  status)
    echo "Version (configured): $SAFEAI_VERSION${SAFEAI_PREVIOUS:+   previous: $SAFEAI_PREVIOUS}"
    docker ps -a --filter "name=^/${NAME}$" --format "Container: {{.Status}}" || true
    docker exec "$NAME" python -m safeai_observe status 2>/dev/null | python3 -c "
import json,sys
d=json.load(sys.stdin); print('Health:', d['status'])
for c in d['checks']: print(f\"  [{c['status']:4}] {c['title']}: {c['detail']}\")" || echo "Health: not answering" ;;
  logs)    docker logs --tail "${1:-200}" ${2:+-f} "$NAME" ;;
  setup-code) docker exec "$NAME" python -m safeai_observe setup-code ;;
  licence|license) need_root    # where the evaluation or licence stands, and the code to ask for a key; "licence add KEY" (or: licence add < key.txt)
           if [ "${1:-}" = add ] && [ -z "${2:-}" ]; then docker exec -i "$NAME" python -m safeai_observe licence add
           else docker exec "$NAME" python -m safeai_observe licence "$@"; fi ;;
  provider-health) need_root    # what connected cloud providers report about themselves; "provider-health read" reads them now
           docker exec "$NAME" python -m safeai_observe provider-health "$@" ;;
  net-links) need_root          # routing neighbours of your own devices; "net-links read" reads them now
           docker exec "$NAME" python -m safeai_observe net-links "$@" ;;
  cloud-links) need_root        # every cloud link with its state; "cloud-links read" reads them now
           docker exec "$NAME" python -m safeai_observe cloud-links "$@" ;;
  cloud-numbers) need_root      # traffic, connections, errors and latency per cloud link, against normal; "read" reads now
           docker exec "$NAME" python -m safeai_observe cloud-numbers "$@" ;;
  collector-enroll) need_root; [ "${COLLECTOR:-0}" = 1 ] || die "this server isn't installed as a collector (install.sh --collector)"
           docker run --rm -v "$DATA:/var/lib/safeai" --user "$UIDGID" --read-only --tmpfs /tmp:rw,size=64m --cap-drop ALL --security-opt no-new-privileges \
             "$IMG:$SAFEAI_VERSION" collector enroll "$@" && "$0" restart >/dev/null && echo "Enrolled; the collector reads its devices and reports to the central SafeAI." ;;
  collector-once) need_root; docker exec "$NAME" python -m safeai_observe collector once ;;
  seed)    need_root; [ -f "${1:-}" ] || die "usage: safeaictl seed SETUP_FILE   (zero-touch setup file; applied when SafeAI starts, then wiped)"
           install -o "${SAFEAI_UID:-10001}" -g "${SAFEAI_GID:-10001}" -m 0600 "$1" "$DATA/seed.conf"; rm -f "$DATA/seed.error.json"
           "$0" restart >/dev/null; for _ in $(seq 1 60); do [ -f "$DATA/seed.conf" ] || break; sleep 1; done
           if [ -f "$DATA/seed.error.json" ]; then echo "Setup file NOT applied:"; grep -o '"problems": \[[^]]*\]' "$DATA/seed.error.json"; exit 2; fi
           echo "Setup file applied." ;;
  version) echo "$SAFEAI_VERSION" ;;
  backup)  need_root; f=$(backup_now "$@"); echo "Backup: $DATA/backups/$f"
           if [ "${1:-}" = "--with-key" ]; then echo "This backup CONTAINS the key that decrypts saved passwords. Store it like a password."; fi ;;
  eol-update) need_root; [ -f "${1:-}" ] || die "usage: safeaictl eol-update eol_data.json"
           docker exec -i "$NAME" python -m safeai_observe eol-update < "$1" ;;
  vulns-update) need_root; [ -f "${1:-}" ] || die "usage: safeaictl vulns-update kev_data.json"
           docker exec -i "$NAME" python -m safeai_observe vulns-update < "$1" ;;
  verify-backup) need_root      # a restore drill: open, check and extract a backup into a scratch folder; the live data isn't touched
           f=${1:-$(ls -1t "$DATA/backups"/safeai-backup-*.tar.gz 2>/dev/null | head -1)}; [ -n "$f" ] || die "no backups yet"
           base=$(basename "$f"); [[ "$base" =~ ^[A-Za-z0-9._-]+$ ]] && [ -f "$DATA/backups/$base" ] || die "no such backup in $DATA/backups: $f"
           docker exec "$NAME" python -m safeai_observe verify-backup "/var/lib/safeai/backups/$base" | python3 -c "
import json,sys
r=json.load(sys.stdin); print(('OK' if r['ok'] else 'PROBLEM') + ': ' + r['file'])
if r.get('files') is not None: print(f\"  {r['files']} files, {r.get('devices', 0)} devices, {r.get('changes', 0)} change records, keys {'included' if r.get('with_key') else 'not included'}\")
for p in r['problems']: print('  - ' + p)
sys.exit(0 if r['ok'] else 1)" ;;
  change-audit) need_root   # one page on the last days' changes, from SafeAI's own records
           cdays=7; cout=safeai-change-audit.html
           while [ $# -gt 0 ]; do case "$1" in
             --days) cdays=${2:?--days needs a number}; shift 2 ;;
             --out) cout=${2:?--out needs a file name}; shift 2 ;;
             *) die "usage: safeaictl change-audit [--days 7] [--out change-audit.html]" ;;
           esac; done
           ct=/tmp/safeai-change-audit-$$.html
           docker exec "$NAME" python -m safeai_observe change-audit --days "$cdays" --out "$ct" | grep -v '^Report: ' || true
           docker cp -q "$NAME:$ct" "$cout" 2>/dev/null && echo "Report: $cout" || die "the change audit didn't produce a report (see the message above)"
           docker exec -u 0 "$NAME" rm -f "$ct" >/dev/null 2>&1 || true ;;
  replay)  need_root      # an outage replay from configuration files (two files, or two folders): the files are read, never stored
           [ -e "${1:-}" ] && [ -e "${2:-}" ] || die "usage: safeaictl replay BEFORE AFTER [--other FILE]... [--name NAME] [--symptom TEXT] [--out report.html]"
           rb=$1; ra=$2; shift 2; rout=safeai-outage-replay.html; rargs=(); rt=/tmp/safeai-replay-$$
           docker exec -u 0 "$NAME" mkdir -p "$rt/o"
           trap 'docker exec -u 0 "$NAME" rm -rf "$rt" >/dev/null 2>&1 || true' EXIT
           docker cp -q "$rb" "$NAME:$rt/before"; docker cp -q "$ra" "$NAME:$rt/after"
           while [ $# -gt 0 ]; do case "$1" in
             --out) rout=${2:?--out needs a file name}; shift 2 ;;
             --other) [ -f "${2:-}" ] || die "no such file: ${2:-}"; docker cp -q "$2" "$NAME:$rt/o/$(basename "$2")"; rargs+=(--other "$rt/o/$(basename "$2")"); shift 2 ;;
             --symptom|--label|--name) rargs+=("$1" "${2:-}"); shift 2 ;;
             *) die "unknown option: $1" ;;
           esac; done
           docker exec -u 0 "$NAME" chmod -R a+rX "$rt"; docker exec -u 0 "$NAME" chmod a+rwx "$rt"
           docker exec "$NAME" python -m safeai_observe replay "$rt/before" "$rt/after" "${rargs[@]}" --out "$rt/report.html" | grep -v '^Report: ' || true
           docker cp -q "$NAME:$rt/report.html" "$rout" 2>/dev/null && echo "Report: $rout" || die "the replay didn't produce a report (see the message above)" ;;
  restore) need_root; [ -n "${1:-}" ] || die "usage: safeaictl restore FILE"
           if pre=$(backup_now --kind=restore 2>/dev/null); then echo "Backup of the data as it was, before restoring: $pre"
           else echo "SafeAI isn't answering, so no backup of the current data was taken first."; fi
           restore_file "$1" "$SAFEAI_VERSION"; run_container "$SAFEAI_VERSION"; wait_healthy "$SAFEAI_VERSION" 120 && echo "Restored and running." || die "SafeAI didn't answer within 2 minutes; see: safeaictl logs" ;;
  upgrade)
    need_root; [ -n "${1:-}" ] || die "usage: safeaictl upgrade safeai-observe-X.Y.Z.tar [--allow-downgrade]"
    tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
    tar --no-same-owner --no-same-permissions -xf "$1" -C "$tmp"; dir=$(find "$tmp" -maxdepth 1 -mindepth 1 -type d | head -1)
    verify_bundle "$dir"; new=$(cat "$dir/VERSION"); old=$SAFEAI_VERSION
    [[ "$new" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "the bundle has an unexpected version: $new"
    [ "$new" != "$old" ] || die "version $new is already installed"
    if ! newer "$new" "$old" && [ "${2:-}" != "--allow-downgrade" ]; then die "$new is older than the installed $old; to go back use 'safeaictl rollback', or add --allow-downgrade"; fi
    # room for the release folder, the image (about 3x its compressed size) and the backup taken before switching
    sz=$(( $(du -sm "$dir" | cut -f1) + 1 )); img=$(du -sm "$dir/images" | cut -f1)
    if [ "$(free_mb /opt)" -lt $((sz + 100)) ] || [ "$(free_mb "$(docker_root)")" -lt $((img * 3 + 200)) ] || [ "$(free_mb "$DATA")" -lt 200 ]; then
      die "not enough free disk space for $new (about $((sz + img * 3)) MB needed). Run 'sudo safeaictl prune' to remove old versions, then try again."
    fi
    echo "Upgrading $old -> $new"
    trap 'rm -rf "$tmp"; [ -f "$RELEASES/$new/.complete" ] || rm -rf "${RELEASES:?}/$new"' EXIT   # never leave a half-copied release
    docker load -i "$dir/images/safeai-observe-$new.tar.gz" >/dev/null
    mkdir -p "$RELEASES/$new"; cp -R "$dir/." "$RELEASES/$new/"; chmod -R u-s,g-s,go-w "$RELEASES/$new"; touch "$RELEASES/$new/.complete"
    pre=$(backup_now --kind=upgrade); echo "Backup before upgrade: $pre"
    setenv SAFEAI_PREVIOUS "$old"; setenv SAFEAI_VERSION "$new"; setenv UPGRADE_BACKUP "$pre"
    run_container "$new"
    if wait_healthy "$new" 180; then
      install -m 0755 "$dir/safeaictl" /usr/local/sbin/safeaictl
      if [ -f "$dir/safeai-helper.timer" ]; then
        install -m 0644 "$dir/safeai-helper.service" "$dir/safeai-helper.timer" /etc/systemd/system/
        systemctl daemon-reload; systemctl enable --now safeai-helper.timer >/dev/null 2>&1 || true
      fi
      SAFEAI_VERSION=$new; SAFEAI_PREVIOUS=$old; prune_releases
      echo "Upgraded to $new. If something is wrong: sudo safeaictl rollback"
    else
      echo "Version $new did not become healthy within 3 minutes; going back to $old."
      docker logs --tail 40 "$NAME" 2>&1 | sed 's/^/  | /' || true
      restore_file "$pre" "$old"; setenv SAFEAI_VERSION "$old"; setenv SAFEAI_PREVIOUS ""
      run_container "$old"; wait_healthy "$old" 120 && echo "Back on $old with the data as it was before the upgrade." || die "rollback started but $old is not answering; see safeaictl logs"
      exit 2
    fi ;;
  rollback)
    need_root; [ -n "${SAFEAI_PREVIOUS:-}" ] || die "no previous version to go back to"
    echo "Going back from $SAFEAI_VERSION to $SAFEAI_PREVIOUS, with the data as it was before the upgrade (changes recorded since then are lost)."
    [ -n "${UPGRADE_BACKUP:-}" ] && restore_file "$UPGRADE_BACKUP" "$SAFEAI_PREVIOUS"
    cur=$SAFEAI_VERSION; setenv SAFEAI_VERSION "$SAFEAI_PREVIOUS"; setenv SAFEAI_PREVIOUS ""; SAFEAI_VERSION=$(grep ^SAFEAI_VERSION= "$ENVF" | cut -d= -f2)
    run_container "$SAFEAI_VERSION"; wait_healthy "$SAFEAI_VERSION" 120 && echo "Now running $SAFEAI_VERSION ($cur is still loaded and can be upgraded to again)." || die "SafeAI didn't answer within 2 minutes; see: safeaictl logs" ;;
  tls-install)
    need_root; [ -f "${1:-}" ] && [ -f "${2:-}" ] || die "usage: safeaictl tls-install CERT.pem KEY.pem (certificate chain first)"
    openssl x509 -noout -in "$1" || die "not a PEM certificate"
    [ "$(openssl x509 -noout -pubkey -in "$1" | sha256sum)" = "$(openssl pkey -pubout -in "$2" | sha256sum)" ] || die "the key doesn't belong to the certificate"
    python3 -c 'import json,sys;print(json.dumps({"cert":open(sys.argv[1]).read(),"key":open(sys.argv[2]).read()}))' "$1" "$2" | in_container tls-install
    docker restart "$NAME" >/dev/null; wait_healthy "$SAFEAI_VERSION" 120 && echo "Certificate installed." || die "SafeAI didn't answer within 2 minutes; see: safeaictl logs" ;;
  ca-install)
    need_root; [ -f "${1:-}" ] || die "usage: safeaictl ca-install CA.pem (your organization's CA certificates, PEM; replaces any installed before)"
    openssl x509 -noout -in "$1" || die "not a PEM certificate"
    in_container ca-install < "$1"; docker restart "$NAME" >/dev/null; wait_healthy "$SAFEAI_VERSION" 120 && echo "SafeAI now also trusts these CAs for its outgoing HTTPS." || die "SafeAI didn't answer within 2 minutes; see: safeaictl logs" ;;
  key-export)
    need_root; [ -n "${1:-}" ] || die "usage: safeaictl key-export FILE"
    ( umask 077; in_container key-export > "$1" ) || die "couldn't read the key (is SafeAI running?)"
    echo "Saved the key that decrypts SafeAI's saved device passwords to $1. Keep it offline, like a password; you need it to restore a backup on a new server." ;;
  key-import)
    need_root; [ -f "${1:-}" ] || die "usage: safeaictl key-import FILE"
    in_container key-import < "$1" || die "not installed"; docker restart "$NAME" >/dev/null; wait_healthy "$SAFEAI_VERSION" 120 && echo "Key installed." || die "SafeAI didn't answer within 2 minutes; see: safeaictl logs" ;;
  verify)  in_container verify ;;
  reset-admin)
    need_root; [ -n "${1:-}" ] || die "usage: safeaictl reset-admin USERNAME"; docker exec -it "$NAME" python -m safeai_observe reset-admin "$1" ;;
  support-bundle)
    need_root; out=/root/safeai-support-$(date -u +%Y%m%dT%H%M%SZ).tar.gz; tmp=$(mktemp -d)
    { echo "configured: $SAFEAI_VERSION previous: ${SAFEAI_PREVIOUS:-}"; uname -a; docker version --format '{{.Server.Version}}'; df -h "$DATA"; free -m; } > "$tmp/system.txt" 2>&1 || true
    in_container support-info > "$tmp/support-info.json" 2>&1 || echo "SafeAI is not answering" >> "$tmp/system.txt"
    docker logs --tail 3000 "$NAME" 2>&1 | sed -E 's/SETUP CODE: [^ ]+/SETUP CODE: (hidden)/' > "$tmp/container.log" || true
    tar -czf "$out" -C "$tmp" . && rm -rf "$tmp" && chmod 600 "$out"
    echo "Support bundle: $out (settings with webhook and heartbeat addresses masked, the device list without account names, status and logs;"
    echo "no passwords, keys, tokens, users or device configurations). Look through it before sending it." ;;
  helper-tick) need_root; [ "${COLLECTOR:-0}" = 1 ] && exit 0
           [ "$(docker inspect -f '{{.State.Running}}' "$NAME" 2>/dev/null)" = true ] || exit 0       # stopped on purpose, or mid-upgrade
           exec 9>/run/safeai-helper.lock; flock -n 9 || exit 0
           helper_alive; helper_restore; helper_alive; helper_copy ;;     # alive again after a restore (it replaces state/)
  backup-copy-key) need_root
           [ -f "$COPYKEY" ] || ssh-keygen -q -t ed25519 -N "" -C "safeai-backup-copy@$(hostname)" -f "$COPYKEY"
           chmod 600 "$COPYKEY"; echo "Add this line to ~/.ssh/authorized_keys of the account on the backup server (ideally one that can only write there):"
           cat "$COPYKEY.pub"; helper_alive ;;
  prune)   need_root; prune_releases; echo "Free space: $(free_mb /opt) MB on /opt, $(free_mb "$(docker_root)") MB for images." ;;
  uninstall)
    need_root; docker rm -f "$NAME" >/dev/null 2>&1 || true
    if [ "${1:-}" = "--purge" ]; then rm -rf "$DATA" /opt/safeai /etc/safeai /usr/local/sbin/safeaictl; echo "SafeAI and all its data removed."
    else echo "Stopped and removed the container. Data kept in $DATA; run 'safeaictl uninstall --purge' to delete it."; fi ;;
  *) cat <<EOF
safeaictl: start | stop | restart | status | logs [N] [-f] | setup-code | licence [add KEY] | provider-health [read] | net-links [read] | cloud-links [read] | cloud-numbers [read] | seed FILE | version | collector-enroll ARGS | collector-once
           backup [--with-key] | verify-backup [FILE] | backup-copy-key | helper-tick | vulns-update FILE | eol-update FILE | restore FILE | upgrade BUNDLE.tar | rollback | prune
           tls-install CERT KEY | ca-install CA.pem | key-export FILE | key-import FILE | reset-admin USER | support-bundle | uninstall [--purge]
           verify  (check the change records' fingerprints)
EOF
  ;;
esac
