#!/bin/bash
# ---------------------------------------------------------------------------
#  Solomon's Vault - Secure Cloud Backup by COiN Services (coinservices.net)
#  Agent + CLI for macOS and Linux.  Works with macOS /bin/bash 3.2.
#
#  Copyright (c) 2026 COiN Services. All rights reserved.
#  Backup engine: restic (https://restic.net), Copyright (c) 2014 Alexander
#  Neumann and contributors, BSD 2-Clause License - see LICENSES/restic-LICENSE.txt.
#  Solomon's Vault is not affiliated with or endorsed by the restic project.
#
#  Usage: solomonsvault <command> [args]
#    status [--offline]   is it working? last backup, Full Disk Access, recent backups
#    run-now [--quick|--test] [--wait]
#                         start a backup now in the background (--quick = Desktop +
#                         Documents of the signed-in user; --test = only the
#                         "Solomon's Vault Test" folder on their Desktop)
#    fda                  (macOS) check that Full Disk Access is granted to the helper
#    enroll <file>        import an enrollment file from COiN Services (root)
#    set-paths <path...>  set SV_PATHS in the config and start the backup schedule (root)
#                         Linux: use after install, or pass --paths to install.sh
#    backup [--if-due]    what the scheduler runs (--if-due: only if >20h since last)
#    prune                client-side retention (zero-knowledge vaults only)
#    check                verify repository + 1% data sample
#    snapshots            list backups for this computer
#    find <pattern>       search backups for a file name (admin)
#    restore [snap] [--include PATH]... [--target DIR]   (admin)
#    ui-find <text> / ui-restore <n>   used by the "Get Back a Lost File" app via sudo
#    testrestore          restore 1-2 random files from the latest backup to a temp
#                         folder, verify, delete, report (weekly from launchd) (root)
#    selfupdate [--force] check the signed update channel and install a newer agent,
#                         with rollback (daily from launchd) (root)
#    install-jobs         (re)write + load the test-restore and update launchd jobs (root)
#    version
# ---------------------------------------------------------------------------
set -uo pipefail

SV_VERSION="1.2.2"
OS="$(uname -s)"
umask 022

# ui-* commands are reachable through a NOPASSWD sudoers rule. sudo already resets
# the environment; also refuse any path overrides there unless explicitly testing.
if [[ -n "${SUDO_UID:-}" && "${SV_ALLOW_ENV_OVERRIDE:-}" != 1 ]]; then
  unset SV_ROOT SV_ETC SV_STATE SV_LOGDIR SV_CACHE SV_RESTIC SV_HOST SV_SELF SV_LAUNCHD_DIR SV_TEST_MODE SV_UPDATE_PUBKEY_FILE SV_UPDATE_CAFILE SV_TEST_BASH SV_TEST_PATH
fi

if [[ "$OS" == "Darwin" ]]; then
  PATH="/usr/bin:/bin:/usr/sbin:/sbin:$PATH"
  if [[ "${SV_TEST_MODE:-}" == 1 && -n "${SV_TEST_PATH:-}" ]]; then PATH="$SV_TEST_PATH:$PATH"; fi   # Linux CI: macOS tool shims
  SV_ROOT="${SV_ROOT:-/Library/SolomonsVault}"
  SV_ETC="${SV_ETC:-$SV_ROOT/etc}"
  SV_STATE="${SV_STATE:-$SV_ROOT/state}"
  SV_LOGDIR="${SV_LOGDIR:-/Library/Logs/SolomonsVault}"
  SV_CACHE="${SV_CACHE:-/Library/Caches/SolomonsVault}"
  SV_RESTIC="${SV_RESTIC:-$SV_ROOT/bin/restic}"
  SV_SELF="${SV_SELF:-$SV_ROOT/bin/solomonsvault}"
  SV_LAUNCHD_DIR="${SV_LAUNCHD_DIR:-/Library/LaunchDaemons}"
else
  SV_ROOT="${SV_ROOT:-/usr/local/libexec/solomonsvault}"
  SV_LAUNCHD_DIR="${SV_LAUNCHD_DIR:-/nonexistent}"  # Linux: never mkdir this; backups use systemd
  SV_ETC="${SV_ETC:-/etc/solomonsvault}"
  SV_LOGDIR="${SV_LOGDIR:-/var/log/solomonsvault}"
  SV_CACHE="${SV_CACHE:-/var/cache/solomonsvault}"
  SV_STATE="${SV_STATE:-$SV_CACHE/state}"
  SV_RESTIC="${SV_RESTIC:-/usr/local/libexec/solomonsvault/restic}"
  SV_SELF="${SV_SELF:-/usr/local/bin/solomonsvault}"
fi
SV_CONFIG="$SV_ETC/config"
SV_VERSION_FILE="$SV_ROOT/VERSION"
SV_HELPER="$SV_ROOT/bin/SolomonsVaultHelper"   # FDA anchor: never replaced or re-signed by updates
SV_SECRETS="$SV_ETC/secrets"          # root:wheel 0600 inside a 0700 folder
SV_EXCLUDES="$SV_ETC/excludes"
LABEL_BACKUP="net.coinservices.solomonsvault.backup"
LABEL_FDA="net.coinservices.solomonsvault.fdacheck"
LOG=""
CLEANUP=""

say()  { local m; m="$(date '+%Y-%m-%d %H:%M:%S') [$1] ${*:2}"; echo "$m"; if [[ -n "$LOG" ]]; then echo "$m" >> "$LOG"; fi; return 0; }
die()  { say ERROR "$*"; exit 1; }
need_root() { [[ $EUID -eq 0 || ( "${SV_TEST_MODE:-}" == 1 && -z "${SUDO_UID:-}" ) ]] || die "Please run: sudo solomonsvault $*"; }
on_exit() { if [[ -n "$CLEANUP" ]]; then eval "$CLEANUP"; fi; }
trap on_exit EXIT
add_cleanup() { CLEANUP="$CLEANUP $1;"; }

# Read KEY=VALUE without executing the file.
kv_get() {  # file key
  local line k
  [[ -r "$1" ]] || return 1
  while IFS= read -r line || [[ -n "$line" ]]; do
    line="${line%$'\r'}"
    [[ -z "$line" || "$line" == \#* ]] && continue
    k="${line%%=*}"
    if [[ "$k" == "$2" ]]; then printf '%s' "${line#*=}"; return 0; fi
  done < "$1"
  return 1
}
cfg() { local v; v="$(kv_get "$SV_CONFIG" "$1" 2>/dev/null)" || v=""; [[ -n "$v" ]] || v="${2:-}"; printf '%s' "$v"; }
is_true() { case "$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')" in 1|true|yes|on) return 0 ;; esac; return 1; }

secret_put() {  # name value  (never passed on a command line)
  local tmp; tmp="$(mktemp "$SV_ETC/.secrets.XXXXXX")" || die "Cannot write secrets"
  chmod 600 "$tmp"
  if [[ -f "$SV_SECRETS" ]]; then grep -v "^$1=" "$SV_SECRETS" > "$tmp" || true; fi
  printf '%s=%s\n' "$1" "$2" >> "$tmp"
  mv -f "$tmp" "$SV_SECRETS"
}
secret_get() { kv_get "$SV_SECRETS" "$1"; }

macos_ver() { sw_vers -productVersion 2>/dev/null || echo 0.0; }
macos_ge() {  # major minor -> true if this macOS >= major.minor
  local v maj min; v="$(macos_ver)"; maj="${v%%.*}"; min="${v#*.}"; min="${min%%.*}"
  [[ "$maj" =~ ^[0-9]+$ ]] || return 1; [[ "$min" =~ ^[0-9]+$ ]] || min=0
  if [[ "$maj" -gt "$1" ]]; then return 0; fi
  [[ "$maj" -eq "$1" && "$min" -ge "$2" ]]
}

default_host() {
  local h=""
  if [[ "$OS" == "Darwin" ]]; then h="$(scutil --get LocalHostName 2>/dev/null || true)"; fi
  [[ -n "$h" ]] || h="$(hostname -s 2>/dev/null || hostname)"
  printf '%s' "$h"
}
SV_HOST="${SV_HOST:-}"
host_name() { if [[ -z "$SV_HOST" ]]; then SV_HOST="$(cfg SV_HOST)"; [[ -n "$SV_HOST" ]] || SV_HOST="$(default_host)"; fi; printf '%s' "$SV_HOST"; }

load_env() {
  [[ -r "$SV_CONFIG" ]] || die "Solomon's Vault is not enrolled on this computer (missing $SV_CONFIG)."
  [[ -x "$SV_RESTIC" ]] || die "Backup engine not found at $SV_RESTIC"
  host_name >/dev/null
  RESTIC_REPOSITORY="$(cfg SV_REPOSITORY)"
  AWS_ACCESS_KEY_ID="$(secret_get AWS_ACCESS_KEY_ID)"         || die "Missing access key"
  AWS_SECRET_ACCESS_KEY="$(secret_get AWS_SECRET_ACCESS_KEY)" || die "Missing secret key"
  RESTIC_PASSWORD="$(secret_get RESTIC_PASSWORD)"             || die "Missing vault password"
  RESTIC_CACHE_DIR="$SV_CACHE"
  export RESTIC_REPOSITORY AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY RESTIC_PASSWORD RESTIC_CACHE_DIR
  mkdir -p "$SV_STATE" "$SV_LOGDIR" "$SV_CACHE"
  chmod 700 "$SV_STATE" "$SV_CACHE" 2>/dev/null || true
}

run_restic() { "$SV_RESTIC" "$@" 2>&1 | tee -a "${LOG:-/dev/null}"; return "${PIPESTATUS[0]}"; }

# ---- one job at a time (portable: mkdir is atomic; flock is not on macOS) ----
LOCKDIR=""
lock_pid() { cat "$SV_CACHE/.lock.d/pid" 2>/dev/null; }
job_running() { local p; p="$(lock_pid)"; [[ -n "$p" ]] && kill -0 "$p" 2>/dev/null; }
lock_or_exit() {
  mkdir -p "$SV_CACHE"
  LOCKDIR="$SV_CACHE/.lock.d"
  if ! mkdir "$LOCKDIR" 2>/dev/null; then
    if job_running; then say WARN "Another Solomon's Vault job is running (pid $(lock_pid)); exiting."; exit 0; fi
    rm -rf "$LOCKDIR"; mkdir "$LOCKDIR" 2>/dev/null || { say WARN "Could not take the job lock; exiting."; exit 0; }
  fi
  echo $$ > "$LOCKDIR/pid"
  # shellcheck disable=SC2016  # expanded later by on_exit
  add_cleanup 'rm -rf "$LOCKDIR"'
}

# ---- monitoring (Healthchecks on status.coinservices.net) ----
mask_url() { printf '%s' "$1" | sed -E 's#/([0-9a-fA-F-]{32,36}|[A-Za-z0-9_-]{20,})(/|$|\?)#/...\2#g'; }
ping_hc() {  # suffix [bodyfile]
  local url base slug res; local -a opts
  url="$(cfg SV_PING_URL)"
  if [[ -n "$url" ]]; then
    url="${url%/}$1"
  else
    base="$(cfg SV_HEALTHCHECK_BASE)"
    [[ -z "$base" ]] && return 0
    slug="$(printf 'sv-%s-%s' "$(cfg SV_CUSTOMER_ID)" "$(host_name)" | tr '[:upper:]' '[:lower:]' | tr -c 'a-z0-9-' '-')"
    url="${base%/}/${slug}${1}?create=1"
  fi
  opts=(-fsS -m 20 --retry 2 -o /dev/null)
  if is_true "$(cfg SV_PING_INSECURE)"; then opts+=(-k); fi
  if [[ -n "${2:-}" && -r "$2" ]]; then
    tail -c 9800 "$2" | curl "${opts[@]}" --data-binary @- "$url" 2>/dev/null; res=$?
  else
    curl "${opts[@]}" "$url" 2>/dev/null; res=$?
  fi
  if [[ $res -eq 0 ]]; then say INFO "Monitoring ping ${1:-/} OK"; else say WARN "Monitoring ping ${1:-/} failed (curl $res) -> $(mask_url "$url")"; fi
  printf '%s %s %s\n' "$(date +%s)" "$([[ $res -eq 0 ]] && echo OK || echo FAIL)" "${1:-/}" > "$SV_STATE/last-ping" 2>/dev/null || true
  return 0
}
ping_suffix() { case "$1" in 0|3) echo /0 ;; *) echo "/$1" ;; esac; }

# ---- macOS Full Disk Access ----
fda_probe() {  # prints OK | MISSING | NOTNEEDED
  if [[ "$OS" != "Darwin" ]]; then echo NOTNEEDED; return; fi
  if ! macos_ge 10 14; then echo NOTNEEDED; return; fi
  if head -c 1 "/Library/Application Support/com.apple.TCC/TCC.db" >/dev/null 2>&1; then echo OK; else echo MISSING; fi
}
fda_record() { printf '%s %s %s\n' "$(date +%s)" "$1" "$2" > "$SV_STATE/fda" 2>/dev/null || true; }

console_user() {
  local u=""
  if [[ "$OS" == "Darwin" ]]; then u="$(stat -f %Su /dev/console 2>/dev/null || true)"; fi
  [[ "$OS" == "Darwin" ]] || u="${SV_CONSOLE_USER:-}"
  [[ "$u" == root || "$u" == loginwindow ]] && u=""
  printf '%s' "$u"
}
user_home() {  # user
  local h=""
  if [[ "$OS" == "Darwin" ]]; then
    h="$(dscl . -read "/Users/$1" NFSHomeDirectory 2>/dev/null | sed -n 's/^NFSHomeDirectory: //p' | head -n 1)"
  else
    h="$(getent passwd "$1" 2>/dev/null | cut -d: -f6)"
  fi
  printf '%s' "$h"
}

default_paths() { if [[ "$OS" == "Darwin" ]]; then echo "/Users"; else echo "${SV_DEFAULT_PATHS:-/home /etc /root}"; fi; }

write_default_excludes() {
  [[ -f "$SV_EXCLUDES" && "${1:-}" != --force ]] && return 0
  if [[ "$OS" == "Darwin" ]]; then
    cat > "$SV_EXCLUDES" <<'EOX'
# Solomon's Vault default excludes for macOS (restic exclude-file syntax)
# --- caches, logs, trash: rebuilt automatically, never worth backing up
/Users/*/Library/Caches
/Users/*/Library/Containers/*/Data/Library/Caches
/Users/*/Library/Group Containers/*/Library/Caches
/Users/*/Library/Logs
/Users/*/Library/Developer
/Users/*/Library/Metadata/CoreSpotlight
/Users/*/Library/Suggestions
/Users/*/Library/Biome
/Users/*/Library/Daemon Containers
/Users/*/Library/Application Support/CloudDocs
/Users/*/Library/Application Support/CrashReporter
/Users/*/Library/Application Support/Google/Chrome/*/Service Worker/CacheStorage
/Users/*/Library/Application Support/Google/Chrome/*/Code Cache
/Users/*/Library/Application Support/Code/Cache
/Users/*/Library/Application Support/Code/CachedData
/Users/*/.Trash
/Users/*/.cache
/Users/*/.npm
/Users/*/.gradle/caches
/Users/Guest
# --- big re-downloadable stuff
/Users/*/Library/Application Support/MobileSync/Backup
/Users/*/Library/Containers/com.docker.docker
/Users/*/Library/Application Support/Steam/steamapps
/Users/*/Library/Application Support/minecraft/assets
/Users/*/Library/Application Support/minecraft/versions
/Users/*/Library/Application Support/minecraft/libraries
/Users/*/Library/Application Support/minecraft/runtime
# --- Photos: keep the originals and the library database, skip previews it can rebuild
/Users/*/Pictures/*.photoslibrary/resources/derivatives
/Users/*/Pictures/*.photoslibrary/resources/caches
/Users/*/Pictures/*.photoslibrary/private/com.apple.photoanalysisd/caches
/Users/*/Pictures/*.photoslibrary/database/search
# --- iCloud Drive placeholders for files that are only in iCloud (.name.icloud)
*.icloud
# --- developer junk and temp files
node_modules
.DS_Store
*.tmp
EOX
  else
    cat > "$SV_EXCLUDES" <<'EOX'
# Solomon's Vault default excludes for Linux (restic exclude-file syntax)
/home/*/.cache
/home/*/.local/share/Trash
/root/.cache
node_modules
*.tmp
EOX
  fi
}

# ---------------------------------------------------------------------------
cmd_enroll() {
  need_root enroll
  local f="${1:-}"; [[ -r "$f" ]] || die "Usage: solomonsvault enroll <sv-enroll-file.txt>"
  local k mode pw pw2
  for k in SV_CUSTOMER_ID SV_MODE SV_REPOSITORY SV_ACCESS_KEY_ID SV_SECRET_ACCESS_KEY; do
    [[ -n "$(kv_get "$f" "$k")" ]] || die "Enrollment file is missing $k"
  done
  mode="$(kv_get "$f" SV_MODE)"
  [[ "$mode" == managed || "$mode" == zeroknowledge ]] || die "Unknown SV_MODE $mode"
  [[ "$mode" == zeroknowledge || -n "$(kv_get "$f" SV_REPO_PASSWORD)" ]] || die "Enrollment file is missing SV_REPO_PASSWORD"

  mkdir -p "$SV_ETC" "$SV_LOGDIR" "$SV_CACHE" "$SV_STATE"
  chmod 700 "$SV_ETC" "$SV_CACHE" "$SV_STATE"
  local host; host="$(cfg SV_HOST)"; [[ -n "$host" ]] || host="$(default_host)"
  local oldmask; oldmask="$(umask)"; umask 077
  {
    echo "# Solomon's Vault by COiN Services - configuration (no secrets in this file)"
    for k in SV_CUSTOMER_ID SV_CUSTOMER_NAME SV_MODE SV_REPOSITORY SV_HEALTHCHECK_BASE SV_PING_URL SV_RESTORE_PING_URL SV_PING_INSECURE SV_SUPPORT_EMAIL SV_SUPPORT_CONTACT; do
      echo "$k=$(kv_get "$f" "$k" || true)"
    done
    echo "SV_HOST=$host"
    echo "SV_PATHS=$(default_paths)"
    echo "SV_UPLOAD_LIMIT_KIB=0"
    echo "SV_DUE_HOURS=20"
    echo "SV_KEEP_DAILY=14"
    echo "SV_KEEP_WEEKLY=8"
    echo "SV_KEEP_MONTHLY=12"
    echo "SV_AUTO_UPDATE=true"
    echo "SV_UPDATE_CHANNEL=stable"
  } > "$SV_CONFIG"
  write_default_excludes
  umask "$oldmask"
  chmod 600 "$SV_CONFIG"; chmod 644 "$SV_EXCLUDES"

  secret_put AWS_ACCESS_KEY_ID "$(kv_get "$f" SV_ACCESS_KEY_ID)"
  secret_put AWS_SECRET_ACCESS_KEY "$(kv_get "$f" SV_SECRET_ACCESS_KEY)"
  if [[ "$mode" == zeroknowledge ]]; then
    echo "Zero-knowledge mode: choose your Vault password. COiN Services will NOT have a copy."
    echo "If you lose it, nobody can recover your backups. Write it down and keep it safe."
    while :; do
      read -r -s -p "Vault password (min 12 chars): " pw; echo
      read -r -s -p "Confirm Vault password: " pw2; echo
      [[ "$pw" == "$pw2" && ${#pw} -ge 12 ]] && break
      echo "Passwords did not match or were too short."
    done
    secret_put RESTIC_PASSWORD "$pw"; pw=""; pw2=""
  else
    secret_put RESTIC_PASSWORD "$(kv_get "$f" SV_REPO_PASSWORD)"
  fi

  load_env
  LOG="$SV_LOGDIR/setup-$(date +%Y%m%d-%H%M%S).log"
  say INFO "Checking that this computer can open vault $(cfg SV_CUSTOMER_ID) ..."
  if ! run_restic cat config --no-lock >/dev/null; then
    if [[ "$mode" == zeroknowledge ]]; then
      say INFO "Initializing your new encrypted vault..."
      run_restic init || die "Vault initialization failed. See $LOG"
    else
      die "Could not open the vault. Check the internet connection and the enrollment file, or call COiN Services. Log: $LOG"
    fi
  fi
  say INFO "Solomon's Vault enrolled: customer $(cfg SV_CUSTOMER_ID), computer name $(host_name)."
}

# Install a /usr/bin symlink so `sudo solomonsvault` works on distros whose
# sudo secure_path does not include /usr/local/bin (RHEL, AlmaLinux, Fedora).
ensure_linux_sudo_symlink() {
  [[ "$OS" == "Linux" ]] || return 0
  test_mode && return 0
  local src="${SV_SELF:-/usr/local/bin/solomonsvault}" dest=/usr/bin/solomonsvault t=""
  [[ -x "$src" ]] || return 0
  if [[ -e "$dest" || -L "$dest" ]]; then
    if [[ -L "$dest" ]]; then
      t="$(readlink -f "$dest" 2>/dev/null || readlink "$dest")"
      srcf="$(readlink -f "$src" 2>/dev/null || printf '%s' "$src")"
      if [[ "$t" == "$src" || "$t" == "$srcf" ]]; then
        return 0
      fi
      say WARN "$dest is a symlink to $t; leaving it alone. Use: sudo $src"
      return 1
    fi
    say WARN "$dest already exists and is not a symlink; sudo may need: sudo $src"
    return 1
  fi
  ln -sfn "$src" "$dest"
}

# Write SV_PATHS and (on Linux) start the already-enabled backup/prune timers.
# Timers are not started at install time unless paths were given with --paths,
# so a first backup cannot run against the default /home /etc /root by accident.
cmd_set_paths() {
  need_root set-paths
  local from_config=0 p paths=""
  if [[ "${1:-}" == --from-config ]]; then
    from_config=1
    shift
    [[ $# -eq 0 ]] || die "Usage: solomonsvault set-paths --from-config"
  fi
  [[ -r "$SV_CONFIG" ]] || die "Solomon's Vault is not enrolled on this computer (missing $SV_CONFIG)."
  if [[ $from_config -eq 1 ]]; then
    paths="$(cfg SV_PATHS)"
    [[ -n "$paths" ]] || die "SV_PATHS is not set in $SV_CONFIG. Run: sudo solomonsvault set-paths /path /path"
  else
    [[ $# -gt 0 ]] || die "Usage: solomonsvault set-paths <path...>   or   solomonsvault set-paths --from-config"
    for p in "$@"; do
      [[ "$p" == /* ]] || die "Backup paths must be absolute (got: $p)"
      case "$p" in
        *" "*|*$'\n'*|*$'\t'*) die "Backup paths cannot contain spaces or newlines: $p" ;;
      esac
      if [[ ! -e "$p" ]]; then say WARN "Path does not exist yet (it will be used when it does): $p"; fi
      paths="${paths:+$paths }$p"
    done
    cfg_set SV_PATHS "$paths" || die "Could not write $SV_CONFIG"
    chmod 600 "$SV_CONFIG" 2>/dev/null || true
  fi
  say INFO "Backup paths set to: $paths"
  if [[ "$OS" == "Linux" ]]; then
    ensure_linux_sudo_symlink || true
    if test_mode; then
      say INFO "Test mode: not starting systemd timers."
      return 0
    fi
    command -v systemctl >/dev/null || die "systemd is required to start the backup schedule."
    systemctl daemon-reload 2>/dev/null || true
    systemctl enable solomonsvault-backup.timer solomonsvault-prune.timer
    systemctl start solomonsvault-backup.timer solomonsvault-prune.timer
    echo "Nightly backups are now scheduled. Next backup: $(systemctl show solomonsvault-backup.timer -p NextElapseUSecRealtime --value 2>/dev/null || echo 'see systemctl list-timers')"
    echo "Run one now (optional): sudo systemctl start solomonsvault-backup"
  else
    say INFO "Paths saved. The existing backup schedule will use them on the next run."
  fi
}

is_due() {
  local last now hours
  last="$(cut -d' ' -f1 "$SV_STATE/last-full-success" 2>/dev/null)"; [[ "$last" =~ ^[0-9]+$ ]] || last=0
  hours="$(cfg SV_DUE_HOURS 20)"; [[ "$hours" =~ ^[0-9]+$ ]] || hours=20
  now="$(date +%s)"
  [[ $((now - last)) -ge $((hours * 3600)) ]]
}
low_battery() {  # macOS laptops: skip scheduled runs on battery below 30%
  [[ "$OS" == "Darwin" ]] || return 1
  local b pct; b="$(pmset -g batt 2>/dev/null)" || return 1
  printf '%s' "$b" | grep -q "Battery Power" || return 1
  pct="$(printf '%s' "$b" | grep -Eo '[0-9]+%' | head -n 1 | tr -d '%')"
  [[ "$pct" =~ ^[0-9]+$ && "$pct" -lt 30 ]]
}

summary_line() {  # mode rc log seconds fda
  local snap added proc errs status out cerrs cskip csize
  snap="$(sed -n 's/^snapshot \([0-9a-f]*\) saved.*/\1/p' "$3" | tail -n 1)"
  added="$(sed -n 's/^Added to the repository: //p' "$3" | tail -n 1)"
  proc="$(sed -n 's/^processed //p' "$3" | tail -n 1)"
  # 1.2.1: "state errors cloud_errors" - rc 3 where every unreadable file is a cloud file -> OK
  out="$(backup_outcome "$2" "$3")"; status="${out%% *}"; out="${out#* }"; errs="${out%% *}"; cerrs="${out#* }"
  cskip="$(sed -n 's/.*Cloud-only files skipped (online-only, not on this Mac): \([0-9]*\) files, \([0-9.]* [A-Za-z]*\).*/\1/p' "$3" | tail -n 1)"
  csize="$(sed -n 's/.*Cloud-only files skipped (online-only, not on this Mac): \([0-9]*\) files, \([0-9.]* [A-Za-z]*\).*/\2/p' "$3" | tail -n 1 | tr -d ' ')"
  printf 'host=%s customer=%s action=backup-%s rc=%s status=%s snapshot=%s processed="%s" added="%s" errors=%s fda=%s duration=%ss agent=%s update=%s restoretest=%s cloud_skipped=%s cloud_skipped_size=%s cloud_errors=%s' \
    "$(host_name)" "$(cfg SV_CUSTOMER_ID)" "$1" "$2" "$status" "${snap:--}" "${proc:--}" "${added:--}" "$errs" "$5" "$4" "$SV_VERSION" "$(update_summary)" "$(testrestore_summary)" "${cskip:--}" "${csize:--}" "$cerrs"
  return 0
}

summary_info() {  # rc log -> extra INFO/WARN lines for the ping body (nothing when there is nothing to say)
  local out errs cerrs cskip csize cnote
  out="$(backup_outcome "$1" "$2")"; out="${out#* }"; errs="${out%% *}"; cerrs="${out#* }"
  cskip="$(sed -n 's/.*Cloud-only files skipped (online-only, not on this Mac): \([0-9]*\) files, .*/\1/p' "$2" | tail -n 1)"
  csize="$(sed -n 's/.*Cloud-only files skipped (online-only, not on this Mac): [0-9]* files, \([0-9.]* [A-Za-z]*\).*/\1/p' "$2" | tail -n 1 | tr -d ' ')"
  cnote=""; grep -q 'Cloud-only files skipped (online-only, not on this Mac): .*(count incomplete)' "$2" 2>/dev/null && cnote=" (count incomplete)"
  if [[ -n "$cskip" && "$cskip" != 0 ]]; then
    printf 'INFO: skipped %s cloud-only files, %s%s - they are online-only (iCloud Drive/OneDrive/Dropbox placeholders) and are not in this backup\n' "$cskip" "$csize" "$cnote"
  fi
  if [[ "$cerrs" -gt 0 ]]; then
    if [[ "$cerrs" -eq "$errs" ]]; then printf 'INFO: %s cloud file read error(s) ignored; no other read errors\n' "$cerrs"
    else printf 'WARN: %s real read error(s) plus %s cloud file error(s)\n' "$((errs - cerrs))" "$cerrs"; fi
  fi
  return 0
}

# ---- 1.2.1: online-only cloud files (iCloud Drive "Optimize Mac Storage", OneDrive/Dropbox/
#      Google Drive File Provider). Dataless files carry SF_DATALESS (0x40000000); reading one makes
#      macOS download it. restic >= 0.19 skips them with --exclude-cloud-files on macOS 14+ (Sonoma);
#      older macOS still downloads them. restic does not count them, so we do (stat only, no reads).
cloud_roots() {  # backup paths... -> existing cloud folders inside them, one per line
  local p h
  for p in "$@"; do
    for h in "$p" "$p"/*; do
      [[ -d "$h/Library/Mobile Documents" ]] && printf '%s\n' "$h/Library/Mobile Documents"
      [[ -d "$h/Library/CloudStorage" ]] && printf '%s\n' "$h/Library/CloudStorage"
    done
  done | awk '!seen[$0]++'
}
# Reads "<hexflags> <size>" lines (BSD stat -f '%Xf %z'); prints "<count> <bytes>" of dataless files.
# Portable awk (no and()): SF_DATALESS is bit 2 of the 8th hex digit from the right.
count_dataless() {
  awk '{ h=tolower($1); sub(/^0x/,"",h); while (length(h) < 8) h="0" h
         d=substr(h, length(h)-7, 1); if (index("4567cdef", d) > 0) { n++; b+=$2 } }
       END { printf "%d %.0f\n", n, b }'
}
human_bytes() {  # bytes -> "1.234 GiB"
  awk -v b="$1" 'BEGIN { if (b >= 1073741824) printf "%.3f GiB", b/1073741824; else if (b >= 1048576) printf "%.3f MiB", b/1048576;
                         else if (b >= 1024) printf "%.3f KiB", b/1024; else printf "%d B", b }'
}
restic_ge() {  # major minor -> true if the bundled restic is >= major.minor
  local v maj min; v="$("$SV_RESTIC" version 2>/dev/null | awk '{print $2; exit}')"; maj="${v%%.*}"; min="${v#*.}"; min="${min%%.*}"
  [[ "$maj" =~ ^[0-9]+$ && "$min" =~ ^[0-9]+$ ]] || return 1
  if [[ "$maj" -gt "$1" ]]; then return 0; fi
  [[ "$maj" -eq "$1" && "$min" -ge "$2" ]]
}
cloud_exclude_on() {  # Darwin, restic >= 0.19 that offers the flag, not turned off with SV_EXCLUDE_CLOUD_FILES=0
  [[ "$OS" == "Darwin" ]] || return 1
  [[ "$(cfg SV_EXCLUDE_CLOUD_FILES 1)" == 0 ]] && return 1
  restic_ge 0 19 || return 1
  "$SV_RESTIC" backup --help 2>/dev/null | grep -q -- '--exclude-cloud-files'
}
# rc logfile -> "STATE errors cloud_errors". A cloud error is an error: line about a file inside
# ~/Library/Mobile Documents or ~/Library/CloudStorage (dataless file that could not be fetched).
backup_outcome() {
  local c
  c="$(awk '/^error/ { e++; if ($0 ~ /\/Library\/(Mobile Documents|CloudStorage)\//) c++ } END { printf "%d %d", e, c }' "$2" 2>/dev/null)"
  [[ -n "$c" ]] || c="0 0"
  local e="${c%% *}" k="${c#* }" st
  case "$1" in 0) st=OK ;; 3) st=WARN ;; *) st=FAIL ;; esac
  if [[ "$1" == 3 && "$e" -gt 0 && "$k" -eq "$e" ]]; then st=OK; fi
  printf '%s %s %s\n' "$st" "$e" "$k"
}
cloud_scan_log() {  # backup paths... -> writes the "Cloud-only files skipped" (or warning) line
  local roots r res n b
  roots="$(cloud_roots "$@")"
  [[ -n "$roots" ]] || { say INFO "Cloud-only files skipped (online-only, not on this Mac): 0 files, 0 B"; return 0; }
  res="$(printf '%s\n' "$roots" | while IFS= read -r r; do find "$r" -type f -print0 2>/dev/null | xargs -0 stat -f '%Xf %z' 2>/dev/null; done | count_dataless)"
  n="${res%% *}"; b="${res#* }"
  if macos_ge 14 0; then
    say INFO "Cloud-only files skipped (online-only, not on this Mac): $n files, $(human_bytes "$b")"
  elif [[ "$n" -gt 0 ]]; then
    say WARN "$n cloud-only files ($(human_bytes "$b")) found; macOS $(macos_ver) cannot skip them, so this backup downloads them (macOS 14+ skips them)"
  fi
}

cmd_backup() {
  local if_due=0 mode=full req
  [[ "${1:-}" == --if-due ]] && if_due=1
  load_env
  req="$SV_STATE/run-request"
  if [[ -f "$req" ]]; then
    mode="$(head -n 1 "$req" 2>/dev/null)"; rm -f "$req"
    [[ "$mode" == quick || "$mode" == test ]] || mode=full
  elif [[ $if_due -eq 1 ]]; then
    is_due || exit 0
    if low_battery; then echo "$(date '+%F %T') skipped: on battery below 30%"; exit 0; fi
  fi
  lock_or_exit
  LOG="$SV_LOGDIR/backup-$(date +%Y%m%d-%H%M%S).log"
  local start fda rc limit p sum u h; start="$(date +%s)"
  local -a args paths=()
  say INFO "Solomon's Vault $SV_VERSION $mode backup starting on $(host_name) (customer $(cfg SV_CUSTOMER_ID))"
  fda="$(fda_probe)"
  if [[ -n "${SV_VIA_HELPER:-}" ]]; then fda_record "$fda" launchd; fi
  case "$fda" in
    OK) say INFO "Full Disk Access: OK" ;;
    MISSING) say WARN "Full Disk Access is NOT turned on for SolomonsVaultHelper - Desktop, Documents, Photos and Mail may be skipped. See the setup steps." ;;
  esac
  if [[ "$mode" == full ]]; then ping_hc /start; fi

  if [[ "$mode" != full ]]; then
    u="$(console_user)"; h=""; [[ -n "$u" ]] && h="$(user_home "$u")"
    if [[ -n "$h" && "$mode" == quick ]]; then
      for p in "$h/Desktop" "$h/Documents"; do [[ -d "$p" ]] && paths+=("$p"); done
    elif [[ -n "$h" && -d "$h/Desktop/Solomon's Vault Test" ]]; then
      paths+=("$h/Desktop/Solomon's Vault Test")
    fi
    [[ ${#paths[@]} -gt 0 ]] || say WARN "$mode backup: no signed-in user or folder found; backing up everything instead."
  fi
  if [[ ${#paths[@]} -eq 0 ]]; then
    read -r -a args <<< "$(cfg SV_PATHS "$(default_paths)")"
    for p in "${args[@]}"; do [[ -e "$p" ]] && paths+=("$p"); done
  fi
  if [[ ${#paths[@]} -eq 0 ]]; then
    say ERROR "No backup paths exist"; rc=1
  else
    write_default_excludes
    args=(backup --exclude-file "$SV_EXCLUDES" --exclude-caches --tag solomonsvault --host "$(host_name)" --compression auto)
    [[ "$mode" != full ]] && args+=(--tag "$mode")
    if cloud_exclude_on; then
      args+=(--exclude-cloud-files)
      cloud_scan_log "${paths[@]}" || true
    fi
    limit="$(cfg SV_UPLOAD_LIMIT_KIB 0)"
    if [[ "$limit" =~ ^[0-9]+$ && "$limit" -gt 0 ]]; then args+=(--limit-upload "$limit"); fi
    run_restic "${args[@]}" "${paths[@]}"; rc=$?
    if [[ $rc -eq 3 ]]; then
      if [[ "$(backup_outcome 3 "$LOG")" == OK* ]]; then say INFO "Backup completed. Some online-only cloud files could not be read and were skipped; no other read errors."
      else say WARN "Backup completed with warnings (some files could not be read)."; fi
    fi
  fi
  say INFO "Finished with exit code $rc"
  sum="$(summary_line "$mode" "$rc" "$LOG" "$(( $(date +%s) - start ))" "$fda")"
  printf '%s %s\n' "$(date +%s)" "$sum" > "$SV_STATE/last-run"
  if [[ $rc -eq 0 || $rc -eq 3 ]]; then
    if [[ "$mode" == full ]]; then printf '%s %s\n' "$(date +%s)" "$sum" > "$SV_STATE/last-full-success"
    else printf '%s %s\n' "$(date +%s)" "$sum" > "$SV_STATE/last-$mode-success"; fi
  fi
  { printf '%s\n' "$sum"; summary_info "$rc" "$LOG"; printf '\n'; tail -n 40 "$LOG"; } > "$SV_STATE/ping-body" 2>/dev/null
  if [[ "$mode" == full ]]; then ping_hc "$(ping_suffix "$rc")" "$SV_STATE/ping-body"
  else ping_hc /log "$SV_STATE/ping-body"; fi
  rm -f "$SV_STATE/ping-body"
  find "$SV_LOGDIR" -name '*.log' -mtime +60 -delete 2>/dev/null || true
  return $rc
}

cmd_run_now() {
  need_root run-now
  local mode=full wait=0 fg=0 a before t
  for a in "$@"; do
    case "$a" in --quick) mode="quick" ;; --test) mode="test" ;; --wait) wait=1 ;; --foreground) fg=1 ;; *) die "Unknown option $a" ;; esac
  done
  [[ -r "$SV_CONFIG" ]] || die "Solomon's Vault is not enrolled on this computer yet."
  mkdir -p "$SV_STATE"; chmod 700 "$SV_STATE"
  before="$(cut -d' ' -f1 "$SV_STATE/last-run" 2>/dev/null)"; [[ -n "$before" ]] || before=0
  if job_running; then echo "A backup is already running (pid $(lock_pid)). Check with: sudo solomonsvault status"; return 0; fi
  printf '%s\n' "$mode" > "$SV_STATE/run-request"
  if [[ $fg -eq 1 ]]; then cmd_backup; return $?; fi
  if [[ "$OS" == "Darwin" ]]; then
    launchctl kickstart "system/$LABEL_BACKUP" || die "Could not start the backup job (is Solomon's Vault installed?)"
  elif command -v systemctl >/dev/null 2>&1 && systemctl cat solomonsvault-backup.service >/dev/null 2>&1; then
    systemctl start --no-block solomonsvault-backup.service || die "Could not start solomonsvault-backup.service"
  elif [[ $wait -eq 1 ]]; then
    cmd_backup; return $?
  else
    nohup /bin/bash "$0" backup >/dev/null 2>&1 &
  fi
  echo "Started a $mode backup in the background. Logs: $SV_LOGDIR"
  [[ $wait -eq 1 ]] || { echo "Check on it any time with:  sudo solomonsvault status"; return 0; }
  echo "Waiting for it to finish (Ctrl-C stops waiting; the backup keeps going)..."
  for ((t = 0; t < 7200; t += 5)); do
    sleep 5
    a="$(cut -d' ' -f1 "$SV_STATE/last-run" 2>/dev/null)"
    if [[ -n "$a" && "$a" != "$before" ]] && ! job_running; then
      echo; cut -d' ' -f2- "$SV_STATE/last-run"
      grep -q 'status=FAIL' "$SV_STATE/last-run" && return 1
      return 0
    fi
    printf '.'
  done
  echo; echo "Still running. Check later with: sudo solomonsvault status"
}

cmd_fdacheck() {  # run by launchd through SolomonsVaultHelper
  mkdir -p "$SV_STATE"
  local r; r="$(fda_probe)"
  if [[ -n "${SV_VIA_HELPER:-}" ]]; then fda_record "$r" launchd; else fda_record "$r" terminal; fi
  echo "$r"
}

cmd_fda() {  # ask launchd to run the check exactly the way the nightly backup runs
  need_root fda
  [[ "$OS" == "Darwin" ]] || { echo "Full Disk Access is a macOS setting; nothing to check here."; return 0; }
  if ! macos_ge 10 14; then echo "Full Disk Access: not needed on macOS $(macos_ver)"; return 0; fi
  local before now t r; before="$(cut -d' ' -f1 "$SV_STATE/fda" 2>/dev/null)"; [[ -n "$before" ]] || before=0
  launchctl kickstart -k "system/$LABEL_FDA" >/dev/null 2>&1 || die "The Full Disk Access check job is not loaded. Re-run the installer."
  for ((t = 0; t < 30; t++)); do
    sleep 1
    now="$(cut -d' ' -f1 "$SV_STATE/fda" 2>/dev/null)"
    if [[ -n "$now" && "$now" != "$before" ]]; then
      r="$(cut -d' ' -f2 "$SV_STATE/fda")"
      if [[ "$r" == OK ]]; then echo "Full Disk Access: OK"; return 0; fi
      echo "Full Disk Access: MISSING - turn on SolomonsVaultHelper in Privacy & Security > Full Disk Access"; return 1
    fi
  done
  echo "Full Disk Access: could not tell (the check did not report back). See $SV_LOGDIR/launchd.log"; return 2
}

cmd_prune() {
  load_env; lock_or_exit
  LOG="$SV_LOGDIR/prune-$(date +%Y%m%d-%H%M%S).log"
  if [[ "$(cfg SV_MODE)" != zeroknowledge ]]; then say INFO "Managed vault: retention is handled by COiN Services."; return 0; fi
  run_restic forget --host "$(host_name)" --tag solomonsvault --keep-daily "$(cfg SV_KEEP_DAILY 14)" \
    --keep-weekly "$(cfg SV_KEEP_WEEKLY 8)" --keep-monthly "$(cfg SV_KEEP_MONTHLY 12)" --prune || return $?
  run_restic check --read-data-subset 1%
}

cmd_restore() {
  load_env
  local snap="latest" target="$PWD/Solomons-Vault-Restore"; local -a inc=()
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --include) inc+=(--include "$2"); shift 2 ;;
      --target)  target="$2"; shift 2 ;;
      *) snap="$1"; shift ;;
    esac
  done
  mkdir -p "$target"
  local -a hostarg=(); [[ "$snap" == latest ]] && hostarg=(--host "$(host_name)")
  echo "Restoring snapshot $snap to $target ..."
  run_restic restore "$snap" ${hostarg[@]+"${hostarg[@]}"} --target "$target" ${inc[@]+"${inc[@]}"}
}

ago() {  # epoch -> "2026-11-12 16:40 (3 hours ago)"
  local e="$1" now d w; now="$(date +%s)"; d=$((now - e))
  if [[ $d -lt 120 ]]; then w="just now"; elif [[ $d -lt 7200 ]]; then w="$((d / 60)) minutes ago"
  elif [[ $d -lt 172800 ]]; then w="$((d / 3600)) hours ago"; else w="$((d / 86400)) days ago"; fi
  if [[ "$OS" == "Darwin" ]]; then printf '%s (%s)' "$(date -r "$e" '+%Y-%m-%d %H:%M')" "$w"
  else printf '%s (%s)' "$(date -d "@$e" '+%Y-%m-%d %H:%M')" "$w"; fi
}
state_line() {  # label file
  local e rest
  if [[ -r "$2" ]]; then e="$(cut -d' ' -f1 "$2")"; rest="$(cut -d' ' -f2- "$2")"; printf '%-18s %s\n                   %s\n' "$1" "$(ago "$e")" "$rest"
  else printf '%-18s %s\n' "$1" "none yet"; fi
}

cmd_status() {
  need_root status
  load_env
  local offline=0 e r via arch=""; [[ "${1:-}" == --offline ]] && offline=1
  echo "Solomon's Vault $SV_VERSION by COiN Services"
  echo "Customer:          $(cfg SV_CUSTOMER_ID) $(cfg SV_CUSTOMER_NAME)  (vault type: $(cfg SV_MODE))"
  echo "This computer:     $(host_name)"
  if [[ "$OS" == "Darwin" ]]; then
    [[ "$(sysctl -n hw.optional.arm64 2>/dev/null)" == 1 ]] && arch="Apple silicon" || arch="Intel"
    echo "macOS:             $(macos_ver) ($arch)"
  fi
  echo "Backup engine:     $("$SV_RESTIC" version 2>/dev/null | awk '{print $1" "$2}')"
  if [[ "$OS" == "Darwin" ]]; then
    if launchctl print "system/$LABEL_BACKUP" >/dev/null 2>&1; then echo "Schedule:          ON (checks every hour, backs up once a day)"
    else echo "Schedule:          NOT LOADED - re-run the installer"; fi
    if [[ -r "$SV_STATE/fda" ]]; then
      e="$(cut -d' ' -f1 "$SV_STATE/fda")"; r="$(cut -d' ' -f2 "$SV_STATE/fda")"; via="$(cut -d' ' -f3 "$SV_STATE/fda")"
      echo "Full Disk Access:  $r (checked $(ago "$e") by $via)"
    else echo "Full Disk Access:  not checked yet - run: sudo solomonsvault fda"; fi
  elif command -v systemctl >/dev/null 2>&1; then
    echo "Schedule:          $(systemctl is-active solomonsvault-backup.timer 2>/dev/null || echo unknown)"
  fi
  # shellcheck disable=SC2012
  if job_running; then echo "Running now:       YES (pid $(lock_pid)) - newest log: $(ls -t "$SV_LOGDIR"/backup-*.log 2>/dev/null | head -n 1)"
  else echo "Running now:       no"; fi
  state_line "Last full backup:" "$SV_STATE/last-full-success"
  state_line "Last run:" "$SV_STATE/last-run"
  [[ -r "$SV_STATE/last-test-success" ]] && state_line "Last test backup:" "$SV_STATE/last-test-success"
  [[ -r "$SV_STATE/last-quick-success" ]] && state_line "Last quick backup:" "$SV_STATE/last-quick-success"
  [[ -r "$SV_STATE/last-ping" ]] && state_line "Monitoring ping:" "$SV_STATE/last-ping"
  state_line "Last test restore:" "$SV_STATE/testrestore-last"
  echo "Automatic updates: $(is_true "$(cfg SV_AUTO_UPDATE true)" && echo ON || echo OFF) (channel $(cfg SV_UPDATE_CHANNEL stable)); last result: $(update_summary)"
  if [[ "$OS" == "Darwin" ]]; then
    launchctl print "system/$LABEL_TR" >/dev/null 2>&1 && launchctl print "system/$LABEL_UPD" >/dev/null 2>&1 \
      && echo "Weekly jobs:       test restore + update check ON" || echo "Weekly jobs:       NOT LOADED - run: sudo solomonsvault install-jobs"
  fi
  if [[ $offline -eq 0 ]]; then
    echo; echo "Backups of this computer in the vault (newest last):"
    "$SV_RESTIC" snapshots --host "$(host_name)" --no-lock --compact 2>&1 | tail -n 12
  fi
}

# ---------------------------------------------------------------------------
#  1.2.0: weekly automatic test restore + signed self-update.
#  Both run from launchd through /bin/bash (NOT through SolomonsVaultHelper, whose
#  command whitelist is never changed - a new helper binary would lose its Full
#  Disk Access grant). The test restore therefore cannot always read the live copy
#  of a protected file; that is reported as live=no-access, not as a failure.
# ---------------------------------------------------------------------------
LABEL_TR="net.coinservices.solomonsvault.testrestore"
LABEL_UPD="net.coinservices.solomonsvault.selfupdate"
JOB_CHANGED=0
SV_UPDATE_MANIFEST_FMT="https://status.coinservices.net:22443/sv-updates/@CHANNEL@/macos/sv-latest.json"
SV_UPDATE_KEY_ID="sv-release-2026"
SV_TR_MAX_BYTES=52428800
# regexes live in variables: macOS /bin/bash 3.2 cannot parse ( ) inside an unquoted [[ =~ ]] pattern
RE_VERSION='^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.]+)?$'
RE_PKGNAME='^SolomonsVault-Update-[A-Za-z0-9.-]+-macos\.tgz$'
RE_SHA256='^[0-9a-f]{64}$'
RE_CHANNEL='^[a-z0-9-]{2,20}$'
RE_LICNAME='^[A-Za-z0-9._-]+$'
RE_PINGURL='^https://[A-Za-z0-9.:-]+/ping/[A-Za-z0-9/_-]+$'
# Release public key (RSA-3072, SHA-256 of this PEM text c8eca75d...912d38). Public - safe to embed.
SV_UPDATE_PUBKEY_PEM='-----BEGIN PUBLIC KEY-----
MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAvtiVO5hxE6/RxG/74lj5
bmbt+VS8hxlqZokPALRzRYx27U5zkUuzV8NW4TGuZ53ZFMrjD6wQxid+NcRxujFO
9yaNMa3XBYmDcgq2kiWQnQIPLd/RWIr8pi3Q6kn++OtjFax0U1zTFHO5oKuNm8iH
hL2cwqa/3BdKoQVa0HpxDTUMqr4dyRTMNBpYs+bwh846w0a6UZ+MTL78ZKvkRXJ2
SIbKTx/vq2JftSDDKyaq3YyC1V/8r2vb9Lg9woeVZrDp+5Tjc+F5onkGjCdYwoaC
vIWdpbL6WK9p2J7x/Z7vCJMlGx24ATTS+Z+IgaV+NCdDPq7wmzhFvOQ4peFEkNE+
2eoE8SHX/dw1A/IiYQBbVg8y/tC1W1wstTNxJnwnw7sudas07GoYhebQMRCxjXv6
pMBimkwrI1SA4K+A4qCtuYgFaBT0DSm4awBaTjyyWJBf3ZPhNb0el1Lh5j89Bu+J
r4nkuHr5iD/oXm2vAvD8qzWAb2vUjL6wNgyUnY0MAk3DAgMBAAE=
-----END PUBLIC KEY-----'

test_mode() { [[ "${SV_TEST_MODE:-}" == 1 ]]; }
SV_BASH=/bin/bash; if test_mode && [[ -n "${SV_TEST_BASH:-}" ]]; then SV_BASH="$SV_TEST_BASH"; fi   # tests: run under bash 3.2
sha256_of() { if command -v shasum >/dev/null 2>&1; then shasum -a 256 "$1" | awk '{print $1}'; else sha256sum "$1" | awk '{print $1}'; fi; }
file_size()  { if [[ "$OS" == "Darwin" ]]; then stat -f %z "$1"; else stat -c %s "$1"; fi; }
file_mtime() { if [[ "$OS" == "Darwin" ]]; then stat -f %m "$1"; else stat -c %Y "$1"; fi; }
# What is installed on disk (VERSION file; 1.1.x has none, so read the installed agent), not this running copy.
installed_version() {
  local v; v="$(head -n 1 "$SV_VERSION_FILE" 2>/dev/null | tr -cd '0-9A-Za-z.-')"
  [[ -n "$v" ]] || v="$(sed -n 's/^SV_VERSION="\([0-9A-Za-z.-]*\)"$/\1/p' "$SV_SELF" 2>/dev/null | head -n 1)"
  [[ -n "$v" ]] || v="$SV_VERSION"; printf '%s' "$v"
}
helper_hash() { if [[ -f "$SV_HELPER" ]]; then sha256_of "$SV_HELPER"; else printf 'none'; fi; }

# ver_cmp a b -> prints 1 (a>b), 0, -1. 1.2.0 > 1.2.0-test > 1.1.9
ver_cmp() {
  local a="${1#[vV]}" b="${2#[vV]}" pa="" pb="" i x y
  case "$a" in *-*) pa="${a#*-}"; a="${a%%-*}" ;; esac
  case "$b" in *-*) pb="${b#*-}"; b="${b%%-*}" ;; esac
  local -a A B
  IFS=. read -r -a A <<< "$a"; IFS=. read -r -a B <<< "$b"
  for i in 0 1 2; do
    x="${A[$i]:-0}"; y="${B[$i]:-0}"
    [[ "$x" =~ ^[0-9]+$ ]] || x=0; [[ "$y" =~ ^[0-9]+$ ]] || y=0
    if ((10#$x > 10#$y)); then echo 1; return; fi
    if ((10#$x < 10#$y)); then echo -1; return; fi
  done
  if [[ -z "$pa" && -n "$pb" ]]; then echo 1
  elif [[ -n "$pa" && -z "$pb" ]]; then echo -1
  elif [[ "$pa" > "$pb" ]]; then echo 1
  elif [[ "$pa" < "$pb" ]]; then echo -1
  else echo 0; fi
}

# Set KEY=VALUE in the config (mode 600 kept; --if-missing leaves an existing value alone).
cfg_set() {  # key value [--if-missing]
  local tmp
  if [[ "${3:-}" == --if-missing ]] && grep -q "^$1=" "$SV_CONFIG" 2>/dev/null; then return 0; fi
  tmp="$(mktemp "$SV_ETC/.config.XXXXXX")" || return 1
  chmod 600 "$tmp"
  grep -v "^$1=" "$SV_CONFIG" > "$tmp" 2>/dev/null || true
  printf '%s=%s\n' "$1" "$2" >> "$tmp"
  mv -f "$tmp" "$SV_CONFIG"
}

ping_to() {  # url suffix [bodyfile] [label]
  local url="${1%/}$2" res; local -a opts=(-fsS -m 20 --retry 2 -o /dev/null)
  if is_true "$(cfg SV_PING_INSECURE)"; then opts+=(-k); fi
  if [[ -n "${3:-}" && -r "$3" ]]; then tail -c 9800 "$3" | curl "${opts[@]}" --data-binary @- "$url" 2>/dev/null; res=$?
  else curl "${opts[@]}" "$url" 2>/dev/null; res=$?; fi
  if [[ $res -eq 0 ]]; then say INFO "${4:-Monitoring} ping ${2:-/} OK"; else say WARN "${4:-Monitoring} ping ${2:-/} failed (curl $res) -> $(mask_url "$url")"; fi
  return 0
}

# ---- launchd jobs for the two 1.2.0 tasks (written by install-jobs) ----
write_job_plist() {  # label schedule-xml args...
  local label="$1" sched="$2" a f tmp; shift 2
  f="$SV_LAUNCHD_DIR/$label.plist"; tmp="$f.new.$$"
  {
    cat <<XML
<?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">
<!-- Solomon's Vault by COiN Services (coinservices.net). Written by solomonsvault install-jobs. -->
<plist version="1.0">
<dict>
  <key>Label</key><string>$label</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/bash</string>
    <string>--noprofile</string>
    <string>--norc</string>
    <string>$SV_SELF</string>
XML
    for a in "$@"; do printf '    <string>%s</string>\n' "$a"; done
    cat <<XML
  </array>
$sched
  <key>RunAtLoad</key><false/>
  <key>EnvironmentVariables</key>
  <dict><key>SV_LAUNCHD_JOB</key><string>$label</string></dict>
  <key>LowPriorityIO</key><true/>
  <key>Nice</key><integer>10</integer>
  <key>ProcessType</key><string>Background</string>
  <key>StandardOutPath</key><string>$SV_LOGDIR/launchd.log</string>
  <key>StandardErrorPath</key><string>$SV_LOGDIR/launchd.log</string>
</dict>
</plist>
XML
  } > "$tmp" || return 1
  chmod 644 "$tmp"; chown root:wheel "$tmp" 2>/dev/null || true
  if [[ "$OS" == "Darwin" ]]; then plutil -lint "$tmp" >/dev/null 2>&1 || { rm -f "$tmp"; say ERROR "$label.plist failed plutil -lint"; return 1; }; fi
  if [[ -f "$f" ]] && cmp -s "$tmp" "$f"; then rm -f "$tmp"; JOB_CHANGED=0; return 0; fi
  mv -f "$tmp" "$f"; JOB_CHANGED=1
}
job_loaded() { [[ "$OS" == "Darwin" ]] || return 0; launchctl print "system/$1" >/dev/null 2>&1; }
# Reload a job only when its plist changed or it is not loaded. Never boot out the job we are
# running inside (launchd would kill this very process, e.g. the self-update mid-swap): its new
# definition then takes effect at the next restart.
job_sync() {  # label changed(0|1)
  if [[ "${SV_LAUNCHD_JOB:-}" == "$1" ]]; then
    job_loaded "$1" && { [[ "$2" == 1 ]] && say INFO "$1 changed; takes effect after the next restart"; return 0; }
  fi
  if [[ "$2" == 0 ]] && job_loaded "$1"; then return 0; fi
  job_load "$1"
}
job_load() {  # label  (Darwin: (re)load; elsewhere a no-op)
  [[ "$OS" == "Darwin" ]] || return 0
  local i
  launchctl bootout system "$SV_LAUNCHD_DIR/$1.plist" >/dev/null 2>&1 || true
  for i in 1 2 3; do   # bootout is asynchronous; bootstrap can briefly fail with error 5
    launchctl bootstrap system "$SV_LAUNCHD_DIR/$1.plist" 2>/dev/null && return 0
    sleep "$i"
  done
  launchctl load -w "$SV_LAUNCHD_DIR/$1.plist" 2>/dev/null && return 0
  job_loaded "$1"
}
job_unload() { [[ "$OS" == "Darwin" && "${SV_LAUNCHD_JOB:-}" != "$1" ]] || return 0; launchctl bootout system "$SV_LAUNCHD_DIR/$1.plist" >/dev/null 2>&1 || true; }
cmd_install_jobs() {
  need_root install-jobs
  # Linux uses the systemd units shipped with install.sh / set-paths, not launchd.
  # SV_LAUNCHD_DIR defaults to /nonexistent; never create it or write plists there.
  if [[ "$OS" != "Darwin" ]]; then
    return 0
  fi
  local load=1 ctr cup; [[ "${1:-}" == --no-load ]] && load=0
  mkdir -p "$SV_LAUNCHD_DIR" "$SV_LOGDIR"
  # Weekly test restore: Wednesday 13:30 (plus up to 2 h random delay); missed while asleep -> runs on wake.
  write_job_plist "$LABEL_TR" "  <key>StartCalendarInterval</key>
  <dict><key>Weekday</key><integer>3</integer><key>Hour</key><integer>13</integer><key>Minute</key><integer>30</integer></dict>" testrestore --scheduled || return 1
  ctr=$JOB_CHANGED
  # Daily update check: 11:00 (plus up to 6 h random delay).
  write_job_plist "$LABEL_UPD" "  <key>StartCalendarInterval</key>
  <dict><key>Hour</key><integer>11</integer><key>Minute</key><integer>0</integer></dict>" selfupdate --scheduled || return 1
  cup=$JOB_CHANGED
  if [[ $load -eq 1 ]]; then
    job_sync "$LABEL_TR" "$ctr" || { say ERROR "Could not load $LABEL_TR"; return 1; }
    job_sync "$LABEL_UPD" "$cup" || { say ERROR "Could not load $LABEL_UPD"; return 1; }
    if [[ "$OS" == "Darwin" ]]; then
      if ! launchctl print "system/$LABEL_TR" >/dev/null 2>&1 || ! launchctl print "system/$LABEL_UPD" >/dev/null 2>&1; then say ERROR "launchd did not list the new jobs"; return 1; fi
    fi
  fi
  say INFO "Scheduled: weekly test restore ($LABEL_TR) and daily update check ($LABEL_UPD)"
}

jitter() {  # max-seconds  (scheduled runs only; SV_NO_JITTER=1 for tests)
  [[ "${SV_NO_JITTER:-}" == 1 ]] && return 0
  local s=$(( (RANDOM * 32768 + RANDOM) % $1 ))
  say INFO "Waiting $((s / 60)) minutes (random delay so not every computer checks in at once)"
  sleep "$s"
}

wait_idle() {  # max-seconds -> 0 when no backup job is running
  local waited=0 step="${SV_IDLE_POLL:-30}"
  while job_running; do
    [[ $waited -ge $1 ]] && return 1
    [[ $waited -eq 0 ]] && say INFO "A backup is running (pid $(lock_pid)); waiting for it to finish..."
    sleep "$step"; waited=$((waited + step))
  done
  return 0
}
lock_try() {  # like lock_or_exit, but returns 1 instead of exiting
  mkdir -p "$SV_CACHE"; LOCKDIR="$SV_CACHE/.lock.d"
  if ! mkdir "$LOCKDIR" 2>/dev/null; then
    job_running && return 1
    rm -rf "$LOCKDIR"; mkdir "$LOCKDIR" 2>/dev/null || return 1
  fi
  echo $$ > "$LOCKDIR/pid"
  # shellcheck disable=SC2016  # expanded later by on_exit
  add_cleanup 'rm -rf "$LOCKDIR"'
}

# ---------------------------------------------------------------------------
#  Weekly test restore
# ---------------------------------------------------------------------------
# Picks up to N random files from `restic ls --json` output on stdin.
# Output: <pref 0|1>\t<size>\t<path>, preferred (Documents/Desktop/...) first.
tr_pick() {  # count seed
  awk -v n="$1" -v seed="$2" -v max="$SV_TR_MAX_BYTES" '
    BEGIN { srand(seed); np = 0; no = 0 }
    !/"type":"file"/ { next }
    {
      if (!match($0, /"path":"[^"]*"/)) next
      p = substr($0, RSTART + 8, RLENGTH - 9)
      if (p ~ /\\/) next                                  # JSON escapes: skip, keep the parser simple
      if (!match($0, /"size":[0-9]+/)) next
      s = substr($0, RSTART + 7, RLENGTH - 7) + 0
      if (s < 1 || s > max) next
      n2 = split(p, parts, "/"); name = parts[n2]
      if (name ~ /[][*?{}]/) next                        # restic --include would treat these as a pattern
      l = tolower(p)
      if (l ~ /\/library\// || l ~ /\/\./ || l ~ /\/caches?\// || l ~ /\/(tmp|temp)\// || l ~ /\/node_modules\//) next
      if (l ~ /\.(photoslibrary|photolibrary|app|bundle|lproj|framework|sparsebundle)\//) next
      if (l ~ /\.(tmp|temp|part|crdownload|download|icloud|lock|sock|swp|ds_store)$/) next
      if (l ~ /^\/(system|private|usr|bin|sbin|var|cores|volumes|opt)\//) next
      if (l ~ /\/(documents|desktop|pictures|music|movies|downloads|onedrive[^\/]*)\//) {
        np++; if (np <= n) P[np] = s "\t" p; else { r = int(rand() * np) + 1; if (r <= n) P[r] = s "\t" p }
      } else {
        no++; if (no <= n) O[no] = s "\t" p; else { r = int(rand() * no) + 1; if (r <= n) O[r] = s "\t" p }
      }
    }
    END {
      k = 0
      for (i = 1; i <= n && i <= np && k < n; i++) { print "1\t" P[i]; k++ }
      for (i = 1; i <= n && i <= no && k < n; i++) { print "0\t" O[i]; k++ }
    }'
}
# Newest full backup of this computer (tags exactly "solomonsvault", not quick/test): "<id> <time>"
tr_latest_snapshot() {
  "$SV_RESTIC" snapshots --host "$(host_name)" --tag solomonsvault --json --no-lock 2>>"${LOG:-/dev/null}" \
  | tr -d '\n' | awk '{
      n = split($0, S, /\{"time":"/)
      best = ""
      for (i = 2; i <= n; i++) {
        t = substr(S[i], 1, index(S[i], "\"") - 1)
        if (S[i] ~ /"tags":\[[^]]*"(quick|test)"/) continue
        if (!match(S[i], /"id":"[0-9a-f]{64}"/)) continue
        id = substr(S[i], RSTART + 6, 64)
        if (t > bt) { bt = t; best = id }
      }
      if (best != "") print best, bt
    }'
}
iso_to_epoch() {  # 2026-11-14T08:06:45.123456-05:00 | ...Z -> epoch seconds
  local s="$1" b off sg=+ hh=0 mm=0 e
  b="${s:0:19}"; off="${s: -6}"
  local re='^[+-][0-9][0-9]:[0-9][0-9]$'
  if [[ "$off" =~ $re ]]; then sg="${off:0:1}"; hh="${off:1:2}"; mm="${off:4:2}"; fi
  if [[ "$OS" == "Darwin" ]]; then e="$(date -j -u -f '%Y-%m-%dT%H:%M:%S' "$b" +%s 2>/dev/null)"
  else e="$(date -u -d "${b/T/ } UTC" +%s 2>/dev/null)"; fi
  [[ "$e" =~ ^[0-9]+$ ]] || return 1
  if [[ "$sg" == + ]]; then echo $(( e - 10#$hh * 3600 - 10#$mm * 60 )); else echo $(( e + 10#$hh * 3600 + 10#$mm * 60 )); fi
}
tr_folder() {  # path -> coarse folder name for reports (no file names leave the Mac)
  local l; l="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
  case "$l" in
    */documents/*) echo Documents ;; */desktop/*) echo Desktop ;; */pictures/*) echo Pictures ;;
    */music/*) echo Music ;; */movies/*) echo Movies ;; */downloads/*) echo Downloads ;; */onedrive*) echo OneDrive ;;
    *) echo other ;;
  esac
}

cmd_testrestore() {
  need_root testrestore
  local scheduled=0 count=2 a
  for a in "$@"; do case "$a" in --scheduled) scheduled=1 ;; --one) count=1 ;; *) die "Unknown option $a" ;; esac; done
  load_env
  LOG="$SV_LOGDIR/testrestore-$(date +%Y%m%d-%H%M%S).log"
  [[ $scheduled -eq 1 ]] && jitter 7200
  if ! wait_idle "${SV_TR_WAIT_SECS:-10800}"; then say WARN "A backup has been running for over 3 hours; test restore skipped this time."; return 0; fi
  lock_try || { say WARN "Could not take the job lock; test restore skipped this time."; return 0; }
  local rurl start snapinfo snap stime age picks tmp i=0 ok=1 reason="" files=0 bytes=0 livem=0 livet=0
  local _pref size path parent leaf got lsh rsh live res r t0 lines="" sum se
  rurl="$(cfg SV_RESTORE_PING_URL)"; start="$(date +%s)"
  say INFO "Solomon's Vault $SV_VERSION test restore starting on $(host_name) (customer $(cfg SV_CUSTOMER_ID))"
  [[ -n "$rurl" ]] && ping_to "$rurl" /start "" "Test-restore"
  tmp="$SV_STATE/testrestore-tmp"; rm -rf "$tmp"; mkdir -p "$tmp"; chmod 700 "$tmp"
  # shellcheck disable=SC2016
  add_cleanup 'chmod -R u+rwX "$SV_STATE/testrestore-tmp" 2>/dev/null; rm -rf "$SV_STATE/testrestore-tmp"'
  snapinfo="$(tr_latest_snapshot)"
  snap="${snapinfo%% *}"; stime="${snapinfo#* }"
  if [[ -z "$snapinfo" || ${#snap} -ne 64 ]]; then ok=0; reason="no full backup of this computer found (or the vault could not be read)"
  else
    picks="$("$SV_RESTIC" ls --json --no-lock "$snap" 2>>"$LOG" | tr_pick "$count" "${SV_TR_SEED:-$$$(date +%s)}")"
    if [[ -z "$picks" ]]; then ok=0; reason="no suitable files (1 byte - 50 MB) in snapshot ${snap:0:8}"; fi
  fi
  if [[ $ok -eq 1 ]]; then
    while IFS=$'\t' read -r _pref size path; do
      [[ -n "$path" ]] || continue
      i=$((i + 1)); parent="${path%/*}"; leaf="${path##*/}"; [[ -n "$parent" ]] || parent="/"
      mkdir -p "$tmp/$i"; t0="$(date +%s)"
      if [[ "$parent" == / ]]; then
        "$SV_RESTIC" restore "$snap" --include "/$leaf" --target "$tmp/$i" --verify --no-lock >>"$LOG" 2>&1; res=$?
      else
        "$SV_RESTIC" restore "$snap:$parent" --include "/$leaf" --target "$tmp/$i" --verify --no-lock >>"$LOG" 2>&1; res=$?
      fi
      got="$tmp/$i/$leaf"; live="-"
      if [[ $res -ne 0 ]]; then r="FAIL(restic exit $res)"
      elif [[ ! -f "$got" ]]; then r="FAIL(restored file missing)"
      elif [[ "$(file_size "$got")" != "$size" ]]; then r="FAIL(size $(file_size "$got") != $size)"
      else
        r=OK; files=$((files + 1)); bytes=$((bytes + size))
        if [[ ! -e "$path" ]]; then live=gone
        elif ! head -c 1 "$path" >/dev/null 2>&1; then live=no-access
        elif [[ "$(file_size "$path")" == "$size" && "$(file_mtime "$path")" == "$(file_mtime "$got")" ]]; then
          livet=$((livet + 1)); lsh="$(sha256_of "$path")"; rsh="$(sha256_of "$got")"
          if [[ -n "$lsh" && "$lsh" == "$rsh" ]]; then live=sha256-match; livem=$((livem + 1))
          else live=sha256-MISMATCH; r="FAIL(restored copy differs from the unchanged original)"; fi
        else live=changed-since-backup; fi
      fi
      case "$r" in OK) ;; *) ok=0; reason="${reason:+$reason; }file$i $r" ;; esac
      lines="${lines}file$i: ext=$( [[ "$leaf" == *.* ]] && printf '.%s' "${leaf##*.}" | tr '[:upper:]' '[:lower:]' | cut -c1-12 || printf none) size=$size folder=$(tr_folder "$path") result=$r live=$live restore_s=$(( $(date +%s) - t0 ))"$'\n'
      chmod -R u+rwX "$tmp/$i" 2>/dev/null; rm -rf "${tmp:?}/$i"
    done <<< "$picks"
    [[ $files -eq 0 && $ok -eq 1 ]] && { ok=0; reason="nothing was restored"; }
  fi
  age="-"
  if [[ -n "${stime:-}" && "$stime" != "$snapinfo" ]]; then
    se="$(iso_to_epoch "$stime")"
    [[ "$se" =~ ^[0-9]+$ ]] && age=$(( ( $(date +%s) - se ) / 3600 ))
  fi
  sum="host=$(host_name) customer=$(cfg SV_CUSTOMER_ID) action=testrestore status=$([[ $ok -eq 1 ]] && echo OK || echo FAILED) agent=$SV_VERSION snapshot=${snap:0:8} snapshot_time=\"${stime:0:16}\" snapshot_age_h=$age files=$files bytes=$bytes live_sha256=$livem/$livet duration=$(( $(date +%s) - start ))s"
  [[ $ok -eq 1 ]] || sum="$sum reason=\"$reason\""
  say INFO "$sum"
  printf '%s' "$lines" | while IFS= read -r a; do [[ -n "$a" ]] && say INFO "$a"; done
  printf '%s %s\n' "$(date +%s)" "$sum" > "$SV_STATE/testrestore-last"
  { printf '%s\n%s\n' "$sum" "$lines"; tail -n 30 "$LOG"; } > "$SV_STATE/testrestore-body" 2>/dev/null
  if [[ -n "$rurl" ]]; then
    if [[ $ok -eq 1 ]]; then ping_to "$rurl" "" "$SV_STATE/testrestore-body" "Test-restore"; else ping_to "$rurl" /fail "$SV_STATE/testrestore-body" "Test-restore"; fi
  else
    { printf 'TESTRESTORE %s\n' "$([[ $ok -eq 1 ]] && echo OK || echo FAILED)"; cat "$SV_STATE/testrestore-body"; } > "$SV_STATE/testrestore-body2"
    ping_hc /log "$SV_STATE/testrestore-body2"; rm -f "$SV_STATE/testrestore-body2"
  fi
  rm -f "$SV_STATE/testrestore-body"
  find "$SV_LOGDIR" -name 'testrestore-*.log' -mtime +120 -delete 2>/dev/null || true
  [[ $ok -eq 1 ]] && return 0
  return 2
}
testrestore_summary() {  # none | ok:YYYY-MM-DD | FAILED:YYYY-MM-DD
  local f="$SV_STATE/testrestore-last" e d
  [[ -r "$f" ]] || { echo none; return; }
  e="$(cut -d' ' -f1 "$f")"
  if [[ "$OS" == "Darwin" ]]; then d="$(date -r "$e" +%F 2>/dev/null)"; else d="$(date -d "@$e" +%F 2>/dev/null)"; fi
  if grep -q 'status=OK' "$f"; then echo "ok:$d"; else echo "FAILED:$d"; fi
}

# ---------------------------------------------------------------------------
#  Signed self-update
# ---------------------------------------------------------------------------
upd_state_file() { printf '%s' "$SV_STATE/update-state"; }
upd_get() { kv_get "$(upd_state_file)" "$1" 2>/dev/null || true; }
# status: ok | failed | deferred | current | unreachable. A check that cannot reach the server
# keeps the last real result; "current" only keeps "ok" (so a verified check clears an old failure).
upd_save() {  # status to [detail]
  local f prev keep=0 tmp from to time
  f="$(upd_state_file)"; prev="$(upd_get status)"
  if [[ "$1" == unreachable && ( "$prev" == ok || "$prev" == failed || "$prev" == current ) ]]; then keep=1; fi
  if [[ "$1" == current && "$prev" == ok ]]; then keep=1; fi
  tmp="$(mktemp "$SV_STATE/.upd.XXXXXX")" || return 0
  if [[ $keep -eq 1 ]]; then
    from="$(upd_get from)"; to="$(upd_get to)"; time="$(upd_get time)"
    printf 'status=%s\nfrom=%s\nto=%s\ntime=%s\n' "$prev" "$from" "$to" "$time" > "$tmp"
  else
    printf 'status=%s\nfrom=%s\nto=%s\ntime=%s\n' "$1" "${SV_UPD_FROM:-$(installed_version)}" "$2" "$(date +%s)" > "$tmp"
  fi
  printf 'last_check=%s\nlast_result=%s\ndetail=%s\n' "$(date +%s)" "$1" "$(printf '%s' "${3:-}" | tr -d '\n' | cut -c1-200)" >> "$tmp"
  mv -f "$tmp" "$f"; chmod 600 "$f" 2>/dev/null || true
}
update_summary() {  # none | ok:1.1.0>1.2.0 | failed:1.2.1 | deferred:1.2.1 | current | unreachable
  local s; s="$(upd_get status)"
  case "$s" in
    "") echo none ;;
    ok) echo "ok:$(upd_get from)>$(upd_get to)" ;;
    failed|deferred) echo "$s:$(upd_get to)" ;;
    *) echo "$s" ;;
  esac
}
mf_get() {  # manifest-file key -> value (flat JSON written by build-release.sh)
  tr -d '\r\n' < "$1" | grep -Eo "\"$2\"[[:space:]]*:[[:space:]]*(\"[^\"]*\"|[0-9]+)" | head -n 1 \
    | sed -E 's/^"[^"]*"[[:space:]]*:[[:space:]]*//; s/^"//; s/"$//'
}
upd_fetch() {  # url outfile max-bytes timeout
  local -a o=(-fsS --proto "=https" --proto-redir "=https" --max-redirs 0 --max-filesize "$3" -m "$4" --retry 2 -o "$2")
  if test_mode && [[ -n "${SV_UPDATE_CAFILE:-}" ]]; then o+=(--cacert "$SV_UPDATE_CAFILE"); fi
  local code; code="$(curl "${o[@]}" -w '%{http_code}' "$1" 2>>"${LOG:-/dev/null}")" || return 1
  # anything but a plain 200 (e.g. a redirect, which is never followed) counts as "not reachable"
  [[ "$code" == 200 ]] || { rm -f "$2"; say INFO "update server answered HTTP $code for $(mask_url "$1")"; return 1; }
}
upd_verify_sig() {  # manifest sig -> 0 if signed by the release key
  local pem out
  pem="$(mktemp "${TMPDIR:-/tmp}/sv-pub.XXXXXX")" || return 1
  if test_mode && [[ -n "${SV_UPDATE_PUBKEY_FILE:-}" ]]; then cat "$SV_UPDATE_PUBKEY_FILE" > "$pem"; else printf '%s\n' "$SV_UPDATE_PUBKEY_PEM" > "$pem"; fi
  out="$(openssl dgst -sha256 -verify "$pem" -signature "$2" "$1" 2>&1)"; local rc=$?
  rm -f "$pem"
  [[ $rc -eq 0 && "$out" == *"Verified OK"* ]]
}
upd_check_package() {  # tgz workdir version -> extracts to workdir/sv-update after strict checks
  local pkg="$1" w="$2" v="$3" e
  tar -tzf "$pkg" > "$w/list" 2>/dev/null || { echo "package is not a valid .tgz"; return 1; }
  while IFS= read -r e; do
    case "$e" in
      sv-update/|sv-update/bin/|sv-update/bin/solomonsvault|sv-update/VERSION|sv-update/LICENSES/) ;;
      sv-update/LICENSES/*)
        [[ "${e#sv-update/LICENSES/}" =~ $RE_LICNAME ]] || { echo "unexpected file in package: $e"; return 1; } ;;
      *) echo "unexpected file in package: $e"; return 1 ;;
    esac
  done < "$w/list"
  grep -q '^sv-update/bin/solomonsvault$' "$w/list" || { echo "package has no agent script"; return 1; }
  # regular files and folders only (no links, devices, ...)
  if tar -tvzf "$pkg" 2>/dev/null | cut -c1 | grep -qv '^[-d]$'; then echo "package contains links or special files"; return 1; fi
  mkdir -p "$w/x" || return 1
  if ! tar -xzf "$pkg" -C "$w/x" 2>/dev/null; then echo "could not unpack package"; return 1; fi
  [[ "$(head -n 1 "$w/x/sv-update/VERSION" 2>/dev/null)" == "$v" ]] || { echo "package VERSION does not say $v"; return 1; }
  grep -q "^SV_VERSION=\"$v\"\$" "$w/x/sv-update/bin/solomonsvault" || { echo "agent script is not version $v"; return 1; }
  "$SV_BASH" -n "$w/x/sv-update/bin/solomonsvault" 2>/dev/null || { echo "agent script has a syntax error"; return 1; }
  return 0
}

# Swap in a new agent with a rollback copy; run the NEW agent's self-test; put the old one back on failure.
# Never touches SolomonsVaultHelper (its Full Disk Access grant is tied to the exact binary) or restic.
apply_update() {  # srcdir(with bin/solomonsvault, VERSION, LICENSES/) new-version [restore-ping-url]
  local src="$1" nv="$2" rurl="${3:-}" rb="$SV_ROOT/rollback" ov hb l f rc
  ov="$(installed_version)"; hb="$(helper_hash)"
  [[ -f "$src/bin/solomonsvault" ]] || { say ERROR "update source has no agent"; return 22; }
  rm -rf "$rb"; mkdir -p "$rb/LICENSES" "$rb/launchd" || return 22; chmod 700 "$rb"
  cp -p "$SV_SELF" "$rb/solomonsvault" || { say ERROR "could not save the current agent"; return 22; }
  if [[ -f "$SV_VERSION_FILE" ]]; then cp -p "$SV_VERSION_FILE" "$rb/VERSION"; fi
  cp -p "$SV_ROOT/LICENSES/"* "$rb/LICENSES/" 2>/dev/null || true
  cp -p "$SV_CONFIG" "$rb/config" || { say ERROR "could not save the config"; return 22; }
  if [[ "$OS" == "Darwin" ]]; then
    : > "$rb/launchd/absent"
    for l in "$LABEL_TR" "$LABEL_UPD"; do
      if [[ -f "$SV_LAUNCHD_DIR/$l.plist" ]]; then cp -p "$SV_LAUNCHD_DIR/$l.plist" "$rb/launchd/"; else echo "$l" >> "$rb/launchd/absent"; fi
    done
  fi
  printf '%s\n%s\n' "$ov" "$hb" > "$rb/from"
  say INFO "Saved the current version ($ov) to $rb"
  # swap: write next to the target, then mv (a running bash keeps reading the old file)
  if ! { cp "$src/bin/solomonsvault" "$SV_SELF.new" && chmod 755 "$SV_SELF.new" && mv -f "$SV_SELF.new" "$SV_SELF"; }; then
    say ERROR "could not install the new agent"; rollback_update; return 20
  fi
  chown root:wheel "$SV_SELF" 2>/dev/null || true
  printf '%s\n' "$nv" > "$SV_VERSION_FILE.new" && chmod 644 "$SV_VERSION_FILE.new" && mv -f "$SV_VERSION_FILE.new" "$SV_VERSION_FILE"
  if [[ -d "$src/LICENSES" ]]; then mkdir -p "$SV_ROOT/LICENSES"; for f in "$src/LICENSES/"*; do [[ -f "$f" ]] && install -m 644 "$f" "$SV_ROOT/LICENSES/"; done; fi
  cfg_set SV_AUTO_UPDATE true --if-missing; cfg_set SV_UPDATE_CHANNEL stable --if-missing
  [[ -n "$rurl" ]] && cfg_set SV_RESTORE_PING_URL "$rurl"
  say INFO "Running the self-test of $nv ..."
  "$SV_BASH" --noprofile --norc "$SV_SELF" postupdate --expect "$nv" --helper-hash "$hb" 2>&1 | tee -a "${LOG:-/dev/null}"; rc=${PIPESTATUS[0]}
  if [[ $rc -eq 0 ]]; then say INFO "Self-test of $nv passed."; return 0; fi
  say ERROR "Self-test of $nv FAILED (exit $rc). Putting $ov back."
  rollback_update
  return 20
}
rollback_update() {
  local rb="$SV_ROOT/rollback" l
  [[ -f "$rb/solomonsvault" ]] || { say ERROR "No rollback copy found in $rb"; return 1; }
  cp -p "$rb/solomonsvault" "$SV_SELF.new" && mv -f "$SV_SELF.new" "$SV_SELF"
  if [[ -f "$rb/VERSION" ]]; then cp -p "$rb/VERSION" "$SV_VERSION_FILE"; else rm -f "$SV_VERSION_FILE"; fi
  cp -p "$rb/LICENSES/"* "$SV_ROOT/LICENSES/" 2>/dev/null || true
  cp -p "$rb/config" "$SV_CONFIG" && chmod 600 "$SV_CONFIG"
  if [[ "$OS" == "Darwin" ]]; then
    for l in "$LABEL_TR" "$LABEL_UPD"; do
      if grep -qx "$l" "$rb/launchd/absent" 2>/dev/null; then job_unload "$l"; rm -f "$SV_LAUNCHD_DIR/$l.plist"
      elif [[ -f "$rb/launchd/$l.plist" ]]; then
        if cmp -s "$rb/launchd/$l.plist" "$SV_LAUNCHD_DIR/$l.plist"; then job_sync "$l" 0 || true
        else cp -p "$rb/launchd/$l.plist" "$SV_LAUNCHD_DIR/$l.plist"; job_sync "$l" 1 || true; fi
      fi
    done
  fi
  say INFO "Rolled back to $(head -n 1 "$rb/from" 2>/dev/null)."
}

cmd_postupdate() {  # run by the NEW agent right after the swap
  need_root postupdate
  local expect="" hb="" a v
  while [[ $# -gt 0 ]]; do case "$1" in --expect) expect="$2"; shift 2 ;; --helper-hash) hb="$2"; shift 2 ;; *) shift ;; esac; done
  [[ "$SV_VERSION" == "$expect" ]] || die "self-test: running agent is $SV_VERSION, expected $expect"
  "$SV_BASH" -n "$SV_SELF" || die "self-test: syntax error in $SV_SELF"
  grep -q "^SV_VERSION=\"$expect\"\$" "$SV_SELF" || die "self-test: installed agent is not $expect"
  [[ "$(installed_version)" == "$expect" ]] || die "self-test: VERSION file says $(installed_version)"
  if [[ -n "$hb" && "$(helper_hash)" != "$hb" ]]; then die "self-test: SolomonsVaultHelper changed - refusing (Full Disk Access would be lost)"; fi
  load_env
  v="$("$SV_RESTIC" version 2>/dev/null)" || die "self-test: backup engine does not run"
  say INFO "self-test: $v"
  "$SV_RESTIC" cat config --no-lock >/dev/null 2>&1 || die "self-test: cannot open the vault (network or keys)"
  say INFO "self-test: vault opens OK"
  cmd_install_jobs || die "self-test: could not schedule the test-restore / update jobs"
  a="$(cfg SV_AUTO_UPDATE)"; say INFO "self-test: passed (auto-update=${a:-true}, channel=$(cfg SV_UPDATE_CHANNEL stable))"
}

cmd_selfupdate() {
  need_root selfupdate
  local scheduled=0 force=0 murl="" a
  while [[ $# -gt 0 ]]; do
    case "$1" in --scheduled) scheduled=1 ;; --force) force=1 ;; --manifest) murl="${2:-}"; shift ;; *) die "Unknown option $1" ;; esac; shift
  done
  [[ "$OS" == "Darwin" ]] || test_mode || die "Self-update is only for the macOS client."
  [[ -r "$SV_CONFIG" ]] || die "Solomon's Vault is not enrolled on this computer."
  mkdir -p "$SV_STATE" "$SV_LOGDIR"
  LOG="$SV_LOGDIR/update-$(date +%Y%m%d-%H%M%S).log"
  if ! is_true "$(cfg SV_AUTO_UPDATE true)" && [[ $force -eq 0 ]]; then say INFO "Automatic updates are turned off (SV_AUTO_UPDATE=false)."; return 0; fi
  [[ $scheduled -eq 1 ]] && jitter 21600
  local ch url base w cur nv min sz sh pkgurl msg rc skipv skipt
  ch="$(cfg SV_UPDATE_CHANNEL stable)"
  [[ "$ch" =~ $RE_CHANNEL ]] || die "Bad SV_UPDATE_CHANNEL"
  url="${murl:-$(cfg SV_UPDATE_MANIFEST_URL)}"; [[ -n "$url" ]] || url="${SV_UPDATE_MANIFEST_FMT/@CHANNEL@/$ch}"
  [[ "$url" == https://* ]] || die "Update manifest URL must be https"
  base="${url%/*}"; cur="$(installed_version)"
  w="$(mktemp -d "${TMPDIR:-/tmp}/sv-update.XXXXXX")" || die "no temp folder"
  add_cleanup "rm -rf '$w'"
  say INFO "Solomon's Vault $cur update check (channel $ch) -> $(mask_url "$url")"
  if ! upd_fetch "$url" "$w/m.json" 65536 60 || ! upd_fetch "$url.sig" "$w/m.sig" 4096 60; then
    say INFO "Update server not reachable right now; will try again tomorrow."
    upd_save unreachable "" "manifest download failed"; return 0
  fi
  if ! upd_verify_sig "$w/m.json" "$w/m.sig"; then
    msg="manifest signature check FAILED - update refused"; say ERROR "$msg"
    upd_save failed "?" "$msg"; upd_report "UPDATE FAILED $msg"; return 22
  fi
  nv="$(mf_get "$w/m.json" version)"; min="$(mf_get "$w/m.json" minFromVersion)"
  sz="$(mf_get "$w/m.json" size)"; sh="$(mf_get "$w/m.json" sha256)"; pkgurl="$(mf_get "$w/m.json" url)"
  msg=""
  [[ "$(mf_get "$w/m.json" product)" == SolomonsVault ]] || msg="manifest product is wrong"
  [[ "$(mf_get "$w/m.json" platform)" == macos ]] || msg="manifest is not for macOS"
  [[ "$(mf_get "$w/m.json" channel)" == "$ch" ]] || msg="manifest channel is not $ch"
  [[ "$(mf_get "$w/m.json" keyId)" == "$SV_UPDATE_KEY_ID" ]] || msg="manifest key id is not $SV_UPDATE_KEY_ID"
  [[ "$nv" =~ $RE_VERSION ]] || msg="bad version in manifest"
  [[ "$pkgurl" =~ $RE_PKGNAME ]] || msg="bad package name in manifest"
  [[ "$sz" =~ ^[0-9]+$ && "$sz" -gt 0 && "$sz" -le 52428800 ]] || msg="bad package size in manifest"
  [[ "$sh" =~ $RE_SHA256 ]] || msg="bad package hash in manifest"
  if [[ -n "$msg" ]]; then say ERROR "$msg - update refused"; upd_save failed "${nv:-?}" "$msg"; upd_report "UPDATE FAILED $msg"; return 22; fi
  if [[ "$(ver_cmp "$nv" "$cur")" != 1 ]]; then
    say INFO "Up to date ($cur; channel offers $nv)."; upd_save current "$nv" ""; return 0
  fi
  if [[ -n "$min" && "$(ver_cmp "$cur" "$min")" == -1 ]]; then
    msg="$nv needs at least $min installed (this Mac has $cur) - needs a manual upgrade"; say WARN "$msg"
    upd_save failed "$nv" "$msg"; upd_report "UPDATE FAILED $msg"; return 22
  fi
  skipv="$(cut -d' ' -f1 "$SV_STATE/update-skip" 2>/dev/null)"; skipt="$(cut -d' ' -f2 "$SV_STATE/update-skip" 2>/dev/null)"
  if [[ $force -eq 0 && "$skipv" == "$nv" && "$skipt" =~ ^[0-9]+$ && $(( $(date +%s) - skipt )) -lt 259200 ]]; then
    say INFO "$nv failed its self-test and was rolled back less than 3 days ago; not retrying yet."; return 0
  fi
  say INFO "Update available: $cur -> $nv. Downloading..."
  if ! upd_fetch "$base/$pkgurl" "$w/pkg.tgz" "$sz" 900; then
    say INFO "Package download failed; will try again tomorrow."; upd_save unreachable "$nv" "package download failed"; return 0
  fi
  if [[ "$(file_size "$w/pkg.tgz")" != "$sz" || "$(sha256_of "$w/pkg.tgz")" != "$sh" ]]; then
    msg="package size/SHA-256 does not match the signed manifest - update refused"; say ERROR "$msg"
    upd_save failed "$nv" "$msg"; upd_report "UPDATE FAILED $nv $msg"; return 22
  fi
  if ! msg="$(upd_check_package "$w/pkg.tgz" "$w" "$nv")"; then
    say ERROR "$msg - update refused"; upd_save failed "$nv" "$msg"; upd_report "UPDATE FAILED $nv $msg"; return 22
  fi
  if ! wait_idle "${SV_UPDATE_IDLE_WAIT:-1800}" || ! lock_try; then
    say INFO "A backup is running; update to $nv deferred to the next check."; upd_save deferred "$nv" "backup running"; return 0
  fi
  apply_update "$w/x/sv-update" "$nv"; rc=$?
  if [[ $rc -eq 0 ]]; then
    SV_UPD_FROM="$cur"; upd_save ok "$nv" "updated from $cur"
    say INFO "Updated Solomon's Vault $cur -> $nv."; upd_report "UPDATE OK $cur -> $nv"; return 0
  fi
  printf '%s %s\n' "$nv" "$(date +%s)" > "$SV_STATE/update-skip"
  upd_save failed "$nv" "self-test failed; rolled back to $cur"; upd_report "UPDATE FAILED $nv self-test failed; rolled back to $cur"
  return 21
}
upd_report() {  # one-line result -> /log on the main check (+ log tail)
  { printf '%s\nhost=%s customer=%s action=selfupdate agent=%s update=%s\n\n' "$1" "$(host_name)" "$(cfg SV_CUSTOMER_ID)" "$(installed_version)" "$(update_summary)"; tail -n 25 "$LOG" 2>/dev/null; } > "$SV_STATE/update-body"
  ping_hc /log "$SV_STATE/update-body"; rm -f "$SV_STATE/update-body"
}

# In-place upgrade from an older install (run by sv-mac-upgrade.sh from the unpacked NEW agent).
cmd_apply_update() {  # <srcdir> [--restore-ping-url URL] [--no-auto-update]
  need_root apply-update
  local src="${1:-}" rurl="" noauto=0 nv cur rc; shift || true
  while [[ $# -gt 0 ]]; do case "$1" in --restore-ping-url) rurl="${2:-}"; shift ;; --no-auto-update) noauto=1 ;; *) die "Unknown option $1" ;; esac; shift; done
  [[ -d "$src" && -f "$src/bin/solomonsvault" ]] || die "Usage: solomonsvault apply-update <unpacked sv-update folder>"
  [[ -z "$rurl" || "$rurl" =~ $RE_PINGURL ]] || die "--restore-ping-url must be an https .../ping/... URL"
  [[ -r "$SV_CONFIG" && -r "$SV_SECRETS" && -f "$SV_SELF" ]] || die "Solomon's Vault is not installed/enrolled here - use the full installer instead."
  mkdir -p "$SV_STATE" "$SV_LOGDIR"
  LOG="$SV_LOGDIR/upgrade-$(date +%Y%m%d-%H%M%S).log"
  nv="$(head -n 1 "$src/VERSION" 2>/dev/null)"; cur="$(installed_version)"
  [[ "$nv" == "$SV_VERSION" ]] || die "Package VERSION ($nv) does not match this agent ($SV_VERSION)"
  say INFO "Upgrading Solomon's Vault $cur -> $nv on $(host_name) (customer $(cfg SV_CUSTOMER_ID)); SolomonsVaultHelper and restic are left as they are."
  if ! wait_idle "${SV_UPGRADE_IDLE_WAIT:-600}" || ! lock_try; then die "A backup is running. Try again when it has finished (sudo solomonsvault status)."; fi
  apply_update "$src" "$nv" "$rurl"; rc=$?
  if [[ $rc -ne 0 ]]; then
    upd_save failed "$nv" "manual upgrade self-test failed; rolled back to $cur"
    upd_report "UPGRADE FAILED $cur -> $nv (rolled back)"
    die "Upgrade failed and was rolled back to $cur. Log: $LOG"
  fi
  [[ $noauto -eq 1 ]] && cfg_set SV_AUTO_UPDATE false
  if [[ "$cur" == "$nv" ]]; then
    upd_report "UPGRADE OK $nv re-applied"            # same version again: keep the last update result
  else
    SV_UPD_FROM="$cur"; upd_save ok "$nv" "manual upgrade from $cur"
    upd_report "UPGRADE OK $cur -> $nv"
  fi
  say INFO "Upgrade to $nv complete. Log: $LOG"
}

# ---------------------------------------------------------------------------
#  "Get Back a Lost File" back end (called by the app through sudo).
#  Only ever shows and restores files inside the calling user's own home folder,
#  hides Library/caches/hidden files, and never overwrites anything.
# ---------------------------------------------------------------------------
ui_out() { printf '%s\t%s\n' "$1" "$2"; }
UI_UID=""; UI_USER=""; UI_HOME=""
ui_caller() {  # [--uid N, honoured only for real root without sudo, e.g. the admin-password fallback]
  local uid="${SUDO_UID:-}"
  if [[ -z "$uid" && "${1:-}" =~ ^[0-9]+$ ]]; then uid="$1"; fi
  [[ "$uid" =~ ^[0-9]+$ && "$uid" -ne 0 ]] || { ui_out ERR "Please open Get Back a Lost File from your own account."; exit 0; }
  UI_UID="$uid"
  UI_USER="$(id -un "$uid" 2>/dev/null)"
  [[ -n "$UI_USER" ]] && UI_HOME="$(user_home "$UI_USER")"
  if [[ -z "$UI_HOME" || "$UI_HOME" != /* || ! -d "$UI_HOME" || "$UI_HOME" == / ]]; then
    ui_out ERR "I couldn't find your home folder. Please call $(cfg SV_SUPPORT_CONTACT "COiN Services")."; exit 0
  fi
  UI_HOME="${UI_HOME%/}"
}
ui_log() { mkdir -p "$SV_LOGDIR"; echo "$(date '+%F %T') [$UI_USER] $*" >> "$SV_LOGDIR/restore-$(date +%Y%m%d).log" 2>/dev/null || true; }

cmd_ui_find() {
  need_root ui-find
  local uidarg=""
  if [[ "${1:-}" == --uid ]]; then uidarg="${2:-}"; shift 2 || true; fi
  ui_caller "$uidarg"
  local q="$*" bare pattern help results
  help="$(cfg SV_SUPPORT_CONTACT "COiN Services")"
  q="$(printf '%s' "$q" | tr -d '\000-\037' | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"
  bare="$(printf '%s' "$q" | tr -d '*? ')"
  if [[ ${#bare} -lt 2 ]]; then ui_out ERR "Please type at least two letters of the file name."; return 0; fi
  if [[ "$q" == */* ]]; then ui_out ERR "Please type just part of the file name, without any / characters."; return 0; fi
  pattern="$q"; [[ "$pattern" == \** ]] || pattern="*$pattern"; [[ "$pattern" == *\* ]] || pattern="$pattern*"
  [[ -r "$SV_CONFIG" ]] || { ui_out ERR "Solomon's Vault isn't set up on this computer. Please call $help."; return 0; }
  load_env >/dev/null 2>&1 || { ui_out ERR "Couldn't open the backup settings. Please call $help."; return 0; }
  mkdir -p "$SV_STATE/ui"; chmod 700 "$SV_STATE/ui"
  results="$SV_STATE/ui/$UI_UID.tsv"
  ui_log "search '$q'"
  local raw rc; raw="$(mktemp)"; add_cleanup "rm -f '$raw'"
  "$SV_RESTIC" find --long --ignore-case --host "$(host_name)" --no-lock "$pattern" > "$raw" 2>>"$SV_LOGDIR/restore-$(date +%Y%m%d).log"; rc=$?
  if [[ $rc -ne 0 ]]; then
    ui_log "restic find failed rc=$rc"
    if grep -q '^Found matching' "$raw"; then :; else ui_out ERR "Couldn't reach your backups. Check that the internet is working, then try again. If it keeps happening, call $help."; return 0; fi
  fi
  # restic --long lines: mode uid gid size date time path   (headers name the snapshot)
  awk -v home="$UI_HOME/" '
    function hidden(rel,   n, parts, i, name) {
      if (rel ~ /^Library\//) return 1
      if (rel ~ /(^|\/)\./) return 1
      if (rel ~ /\.photoslibrary\// || rel ~ /\.photolibrary\// || rel ~ /\.app\//) return 1
      if (rel ~ /(^|\/)node_modules\//) return 1
      n = split(rel, parts, "/"); name = parts[n]
      if (name ~ /\.icloud$/ || name ~ /\.tmp$/ || name == "Icon\r") return 1
      return 0
    }
    /^Found matching entries in snapshot / { snap = $6; bt = $8 " " $9; next }
    /^-/ {
      line = $0; size = $4; mt = $5 " " $6
      path = line
      sub(/^[^ ]+ +[0-9]+ +[0-9]+ +[0-9]+ +[0-9]+-[0-9]+-[0-9]+ +[0-9]+:[0-9]+:[0-9]+ /, "", path)
      if (index(path, home) != 1) next
      rel = substr(path, length(home) + 1)
      if (rel == "" || hidden(rel)) next
      key = path "\034" mt "\034" size
      if (!(key in best) || bt > best[key]) { best[key] = bt; bsnap[key] = snap; bpath[key] = path; bmt[key] = mt; bsize[key] = size; brel[key] = rel }
    }
    END { for (k in best) printf "%s\t%s\t%s\t%s\t%s\t%s\n", bmt[k], bsize[k], best[k], bsnap[k], bpath[k], brel[k] }
  ' "$raw" | LC_ALL=C sort -r > "$raw.rows"
  add_cleanup "rm -f '$raw.rows'"
  local total; total="$(wc -l < "$raw.rows" | tr -d ' ')"
  if [[ "$total" -eq 0 ]]; then
    if grep -q '^Found matching' "$raw" || "$SV_RESTIC" snapshots --host "$(host_name)" --no-lock --compact 2>/dev/null | grep -q '[0-9a-f]\{8\}'; then
      ui_out ERR "I couldn't find a file with that name in your backups. Try a different part of the name, or call $help."
    else
      ui_out ERR "There are no backups of this computer yet. The first one may still be running - try again later, or call $help."
    fi
    : > "$results"; ui_log "no matches"; return 0
  fi
  head -n 200 "$raw.rows" | awk -F'\t' '
    BEGIN { split("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec", M, " ") }
    function when(dt,   d, t, h, ap) {
      split(substr(dt, 1, 10), d, "-"); split(substr(dt, 12), t, ":")
      h = t[1] + 0; ap = "AM"; if (h >= 12) { ap = "PM"; if (h > 12) h -= 12 }; if (h == 0) h = 12
      return M[d[2] + 0] " " (d[3] + 0) ", " d[1] " " h ":" t[2] " " ap
    }
    function human(b) {
      if (b < 1000) return b " bytes"
      if (b < 1000000) return sprintf("%d KB", (b + 999) / 1000)
      if (b < 1000000000) return sprintf("%.1f MB", b / 1000000)
      return sprintf("%.2f GB", b / 1000000000)
    }
    {
      n = split($6, parts, "/"); name = parts[n]; folder = ""
      for (i = 1; i < n; i++) folder = folder (i > 1 ? "/" : "") parts[i]
      if (folder == "") folder = "your home folder"
      printf "%d\t%s\t%s\t%s\t%s. %s  -  in %s  -  changed %s  -  %s  -  backed up %s\n", NR, $4, $5, name, NR, name, folder, when($1), human($2 + 0), when($3)
    }' > "$results"
  chmod 600 "$results"
  ui_out OK "$total"
  cut -f5- "$results"
  ui_log "found $total"
}

cmd_ui_restore() {
  need_root ui-restore
  local uidarg=""
  if [[ "${1:-}" == --uid ]]; then uidarg="${2:-}"; shift 2 || true; fi
  ui_caller "$uidarg"
  local n="${1:-}" results line snap path name help tmp esc src destdir dest stem ext i
  help="$(cfg SV_SUPPORT_CONTACT "COiN Services")"
  results="$SV_STATE/ui/$UI_UID.tsv"
  [[ "$n" =~ ^[0-9]+$ && -r "$results" ]] || { ui_out ERR "Please search again and pick a file from the list."; return 0; }
  line="$(awk -F'\t' -v n="$n" '$1 == n' "$results" | head -n 1)"
  [[ -n "$line" ]] || { ui_out ERR "Please search again and pick a file from the list."; return 0; }
  snap="$(printf '%s' "$line" | cut -f2)"; path="$(printf '%s' "$line" | cut -f3)"; name="$(printf '%s' "$line" | cut -f4)"
  [[ "$snap" =~ ^[0-9a-f]+$ && "$path" == "$UI_HOME/"* && "$path" != *"/../"* && -n "$name" ]] || { ui_out ERR "Please search again and pick a file from the list."; return 0; }
  load_env >/dev/null 2>&1 || { ui_out ERR "Couldn't open the backup settings. Please call $help."; return 0; }
  ui_log "restore $snap $path"
  tmp="$(mktemp -d "${TMPDIR:-/tmp}/sv-restore.XXXXXX")" || { ui_out ERR "$name couldn't be restored. Please call $help."; return 0; }
  add_cleanup "rm -rf '$tmp'"
  chmod 711 "$tmp"
  # --include takes a pattern: escape glob characters so odd names match exactly
  esc="$(printf '%s' "$path" | sed 's/[][*?\\]/\\&/g')"
  "$SV_RESTIC" restore "$snap" --target "$tmp/r" --include "$esc" --no-lock >>"$SV_LOGDIR/restore-$(date +%Y%m%d).log" 2>&1
  src="$tmp/r$path"
  if [[ ! -f "$src" ]]; then
    ui_log "restore produced no file"
    ui_out ERR "I couldn't get \"$name\" back. Check the internet connection and try again, or call $help."; return 0
  fi
  mv "$src" "$tmp/file" && chown "$UI_UID" "$tmp/file" && chmod u+rw "$tmp/file"
  case "$name" in
    ?*.*) stem="${name%.*}"; ext=".${name##*.}" ;;
    *)    stem="$name"; ext="" ;;
  esac
  for destdir in "$UI_HOME/Desktop/Restored Files" "$UI_HOME/Restored Files"; do
    sudo -u "#$UI_UID" /bin/mkdir -p "$destdir" 2>/dev/null || continue
    dest="$destdir/$name"; i=2
    while sudo -u "#$UI_UID" /bin/test -e "$dest"; do dest="$destdir/$stem ($i)$ext"; i=$((i + 1)); done
    if sudo -u "#$UI_UID" /bin/cp -p -n "$tmp/file" "$dest" 2>/dev/null && sudo -u "#$UI_UID" /bin/test -f "$dest"; then
      ui_log "restored to $dest"
      ui_out OK "$dest"
      return 0
    fi
  done
  ui_log "could not write to Desktop or home"
  ui_out ERR "I got \"$name\" back but couldn't save it to your Desktop. Please call $help."
}

case "${1:-}" in
  enroll)     shift; cmd_enroll "$@" ;;
  set-paths)  shift; cmd_set_paths "$@" ;;
  backup)     shift; cmd_backup "$@" ;;
  run-now)    shift; cmd_run_now "$@" ;;
  fdacheck)   cmd_fdacheck ;;
  fda)        cmd_fda ;;
  prune)      cmd_prune ;;
  check)      load_env; run_restic check --read-data-subset 1% ;;
  status)     shift; cmd_status "$@" ;;
  snapshots)  load_env; run_restic snapshots --host "$(host_name)" --no-lock ;;
  find)       shift; load_env; run_restic find --host "$(host_name)" --no-lock "$@" ;;
  restore)    shift; cmd_restore "$@" ;;
  ui-find)    shift; cmd_ui_find "$@" ;;
  ui-restore) shift; cmd_ui_restore "$@" ;;
  testrestore)  shift; cmd_testrestore "$@" ;;
  selfupdate)   shift; cmd_selfupdate "$@" ;;
  postupdate)   shift; cmd_postupdate "$@" ;;
  install-jobs) shift; cmd_install_jobs "$@" ;;
  apply-update) shift; cmd_apply_update "$@" ;;
  version)    echo "Solomon's Vault $SV_VERSION by COiN Services"; [[ -x "$SV_RESTIC" ]] && "$SV_RESTIC" version; true ;;
  *) sed -n '2,34p' "$0"; exit 2 ;;
esac
