#!/bin/bash
# X9 host installer 2026.12.05.1. Verify this script before running it as root.
set -euo pipefail
umask 077
PATH=/usr/sbin:/usr/bin:/sbin:/bin
export PATH
unset DOCKER_HOST DOCKER_CONTEXT DOCKER_CONFIG X9_INSTALL_TOKEN
export DOCKER_HOST=unix:///var/run/docker.sock
readonly dir=/opt/x9-host state=/var/lib/x9d unit=/etc/systemd/system/x9d.service
readonly release=https://x9si.com/host-install/2026.12.05.1 key_sha=fa45a5dbe92ddb2666b8132139a1e1614b120809bc27febbd24a96afb9b3b645
readonly x9_api=https://host.x9si.com x9_relay=tls://relay.x9si.com:443
readonly probe_tag=x9/probe:3
probe_id_ok() { case "$1" in sha256:e12f9d1763b2e91719e64c9688c993256e33ee9337959c714eebe7e97df7b580|sha256:e69df2c8368c7b61bea0cacf2fa484c68893f84eeb9e73b719353ea59c4c216a) return 0;; *) return 1;; esac; }
fail() { printf 'X9 installer: %s\n' "$*" >&2; exit 1; }
root_dir() { [[ -d "$1" && ! -L "$1" && $(stat -c '%u:%a' -- "$1") = 0:700 ]]; }
owned() { root_dir "$dir" && [[ -f "$dir/.x9-public-install" && ! -L "$dir/.x9-public-install" ]]; }
docker() { /usr/bin/env docker --host unix:///var/run/docker.sock "$@"; }
exists() { [[ -e "$1" || -L "$1" ]]; }
check_effective_unit() {
  local fragment dropins
  fragment=$(systemctl show --property=FragmentPath --value x9d.service) || fail 'Could not inspect x9d.service.'
  dropins=$(systemctl show --property=DropInPaths --value x9d.service) || fail 'Could not inspect x9d.service overrides.'
  [[ -z $dropins ]] || fail "Existing systemd overrides change x9d.service: $dropins. Review and remove the overrides before installing."
  if [[ ${1:-} = before ]]; then
    if [[ -z $fragment ]] && ! exists "$unit"; then return; fi
    [[ $fragment = "$unit" && -f $unit && ! -L $unit ]] && owned && cmp -s "$unit" "$dir/x9d.service" ||
      fail 'An existing x9d.service is not owned by this installer. Resolve the conflict before installing.'
  else
    [[ $fragment = "$unit" ]] || fail 'systemd is using a different x9d.service. Resolve the conflict before installing.'
  fi
}
check_install_target() {
  if exists "$dir"; then owned || fail "$dir is not owned by this installer."; fi
  # Re-read systemd's search path even for an inactive service. A vendor unit or
  # drop-in may not yet be cached, and is-active does not detect enablement.
  systemctl daemon-reload || fail 'Could not reload systemd unit definitions.'
  check_effective_unit before
  if systemctl is-active --quiet x9d.service; then fail 'The daemon is already running. Check systemctl status x9d.service.'; fi
}
cleanup_install() {
  if [[ $restore_files = 1 ]]; then
    local dst i bad=0
    for i in "${!targets[@]}"; do
      dst=${targets[i]}
      if exists "$work/prior/$i"; then cp -a --remove-destination -- "$work/prior/$i" "$dst" || bad=1
      else rm -f -- "$dst" || bad=1; fi
    done
    if [[ $new_dir = 1 ]]; then rmdir -- "$dir" || bad=1; fi
    systemctl daemon-reload || bad=1
    if [[ $bad = 1 ]]; then
      printf 'X9 installer: Could not restore all previous files. Backups remain in %s/prior.\n' "$work" >&2
      return
    fi
  fi
  rm -rf -- "$work"
}
[[ $EUID = 0 ]] || fail 'Run the verified installer with sudo.'
exec 9>/run/x9-public-installer.lock
flock -n 9 || fail 'Another X9 installer is running.'

case "${1:-}" in
  --uninstall)
    [[ $# = 1 ]] || fail 'Use --uninstall alone.'
    owned && [[ -f "$dir/x9d" ]] || fail 'No installation owned by this installer was found.'
    cmp -s "$unit" "$dir/x9d.service" || fail 'The systemd unit was changed. Restore the X9 unit before uninstalling.'
    # Check both before and after stopping so an in flight container start is not silently deleted.
    check_empty() {
      "$dir/x9d" -check-no-rentals || fail 'Cannot confirm there are no X9 rentals. Start Docker, unlist and let rentals finish and clean up before uninstalling.'
    }
    check_empty
    systemctl stop x9d.service
    if ! (check_empty); then
      systemctl start --no-block x9d.service
      fail 'A rental appeared while stopping. The daemon is restarting.'
    fi
    "$dir/x9d" -state "$state" -uninstall || fail 'Cleanup did not finish. Check the messages above and retry uninstall.'
    systemctl disable x9d.service
    rm -- "$unit"
    systemctl daemon-reload
    rm -f -- "$dir/x9d" "$dir/install.sh" "$dir/x9d.service" "$dir/.x9-public-install"
    rmdir -- "$dir"
    printf 'X9 daemon removed. The registration and key remain in %s for reinstalling on this machine.\n' "$state"
    exit 0 ;;
  ''|--token-stdin) [[ $# -le 1 ]] || fail 'Use no arguments, --token-stdin or --uninstall.' ;;
  *) fail 'Use no arguments, --token-stdin or --uninstall.' ;;
esac

[[ $(uname -s) = Linux && $(uname -m) = x86_64 && -d /run/systemd/system ]] || fail 'Use a native x86_64 Linux host running systemd.'
[[ $(uname -r | tr '[:upper:]' '[:lower:]') != *microsoft* ]] || fail 'Use a native Linux host.'
for c in curl openssl sha256sum timeout nvidia-smi nvidia-container-cli ip iptables ip6tables systemctl; do
  command -v "$c" >/dev/null || fail "Missing $c. See the requirements at https://x9si.com/hosts/quickstart/."
done
docker info >/dev/null 2>&1 || fail 'Start the local Docker Engine so root can use /var/run/docker.sock.'
check_install_target
if exists "$state"; then
  root_dir "$state" && [[ -f "$state/.x9-public-install" || -z $(find "$state" -mindepth 1 -maxdepth 1 -print -quit) ]] || fail 'An existing daemon state directory is not owned by this installer.'
fi
indexes=$(nvidia-smi --query-gpu=index --format=csv,noheader,nounits) || fail 'nvidia-smi cannot see the GPU. Check the installed NVIDIA driver.'
mapfile -t gpu <<< "$indexes"
[[ ${#gpu[@]} -ge 1 && ${#gpu[@]} -le 16 ]] || fail 'Use a host with 1 to 16 NVIDIA GPUs.'
for i in "${gpu[@]}"; do [[ $i =~ ^[0-9]+$ ]] || fail 'NVIDIA reported an invalid GPU index.'; done

work=$(mktemp -d /run/x9-host-install.XXXXXXXX)
restore_files=0
trap cleanup_install EXIT
fetch() { curl -q -fsS --proto '=https' --connect-timeout 15 --max-time "$2" "$release/$1" -o "$work/$1" || fail "Could not download $1 from x9si.com."; }
for f in signing-key.pem SHA256SUMS SHA256SUMS.sig; do fetch "$f" 60; done
openssl pkey -pubin -in "$work/signing-key.pem" -outform DER -out "$work/key.der" || fail 'Invalid signing key.'
printf '%s  %s\n' "$key_sha" "$work/key.der" | sha256sum -c --status - || fail 'Signing key fingerprint does not match.'
openssl pkeyutl -verify -pubin -inkey "$work/signing-key.pem" -rawin -in "$work/SHA256SUMS" -sigfile "$work/SHA256SUMS.sig" >/dev/null || fail 'Invalid release signature.'
# The manifest is signed and only has these exact names. Refuse truncation, a mismatched release or unexpected paths.
# These digests are part of the installer pinned by the bootstrap. A different
# manifest signed with the same key, even for the same release, cannot replace them.
mapfile -t sums < "$work/SHA256SUMS"
[[ ${#sums[@]} = 3 && ${sums[0]} =~ ^[0-9a-f]{64}\ \ install\.sh$ ]] || fail 'Unexpected release manifest.'
[[ ${sums[1]} = '74b5ad7bebfb35535f6fd0e6e29ce281378ca496120e361f3c9c22747c071cc2  x9d' && ${sums[2]} = '85c5f4b2a625dbcc65a63f204be0508f719eeb29aa1a8259bbda58b75d246c47  x9-probe.tar.gz' ]] || fail 'Manifest payload does not match this installer.'
install -m 0600 -- "$0" "$work/install.sh"
fetch x9d 120
fetch x9-probe.tar.gz 600
(cd "$work" && sha256sum --check --strict SHA256SUMS) || fail 'Release checksum mismatch.'
if image=$(docker image inspect -f '{{.Id}}' "$probe_tag" 2>/dev/null); then
  probe_id_ok "$image" || fail 'The existing Docker image x9/probe:3 is not approved. Rename it before installing.'
else
  docker load -i "$work/x9-probe.tar.gz" || fail 'Docker could not load the signed GPU test image.'
  image=$(docker image inspect -f '{{.Id}}' "$probe_tag") || fail 'The GPU test image is missing after loading.'
  probe_id_ok "$image" || fail 'Docker loaded an unexpected GPU test image.'
fi
for i in "${gpu[@]}"; do
  cid="$work/probe-$i.cid"
  if ! timeout 60 docker --host unix:///var/run/docker.sock run --cidfile "$cid" --rm --network none --cap-drop ALL --security-opt no-new-privileges \
    --gpus "device=$i" "$image" -seed 706f52f9ccea9f18591bd74a6be1a91a -n 64 >/dev/null; then
    if [[ -s "$cid" ]]; then docker rm -f "$(cat "$cid")" >/dev/null 2>&1 || true; fi
    fail "GPU $i failed the Docker compute test. Check NVIDIA driver and Container Toolkit compatibility and the Docker GPU runtime."
  fi
done

check_install_target
new_dir=0
if ! exists "$dir"; then new_dir=1; fi
targets=("$dir/x9d" "$dir/install.sh" "$dir/x9d.service" "$dir/.x9-public-install" "$unit")
mkdir -- "$work/prior"
for i in "${!targets[@]}"; do
  if exists "${targets[i]}"; then cp -a -- "${targets[i]}" "$work/prior/$i"; fi
done
# Preserve the original files (and its unchanged boot links) if a check after
# writing the candidate fails. Do not roll back a saved machine registration.
restore_files=1
install -d -m 0700 -- "$dir" "$state"
touch -- "$dir/.x9-public-install" "$state/.x9-public-install"
install -m 0755 -- "$work/x9d" "$dir/x9d"
install -m 0700 -- "$work/install.sh" "$dir/install.sh"
cat > "$dir/x9d.service" <<UNIT
[Unit]
Description=X9 host daemon
After=network-online.target docker.service
Wants=network-online.target
Requires=docker.service

[Service]
Type=notify
NotifyAccess=main
Environment=X9_API=$x9_api X9_RELAY=$x9_relay X9_STATE_DIR=$state X9_PROBE_IMAGE=$image X9_MODELS=0
Environment=DOCKER_HOST=unix:///var/run/docker.sock
ExecStart=$dir/x9d
TimeoutStartSec=5min
Restart=on-failure
RestartSec=15s
UMask=0077

[Install]
WantedBy=multi-user.target
UNIT
install -m 0644 -- "$dir/x9d.service" "$unit"
systemctl daemon-reload
check_effective_unit
# If enrollment committed but state.json did not, recover with the original key.
# Never generate a replacement key or reserve another slot in that case.
if [[ ! -s "$state/state.json" && -e "$state/machine.key" ]]; then
  rc=0
  "$dir/x9d" -api "$x9_api" -state "$state" -models-report=false -recover-registration || rc=$?
  [[ $rc == 0 || $rc == 3 ]] || fail 'Registration recovery failed. Keep machine.key, check the message above, and retry.'
fi
if [[ ! -s "$state/state.json" ]]; then
  token=''
  if [[ ${1:-} = --token-stdin ]]; then
    IFS= read -r token || fail 'Supply the install token on stdin, followed by a newline.'
  else
    printf 'X9 install token (input hidden): ' >/dev/tty
    IFS= read -rs token </dev/tty || fail 'Use an interactive terminal or --token-stdin.'
    printf '\n' >/dev/tty
  fi
  [[ $token =~ ^x9it_[A-Za-z0-9_-]{32}$ ]] || fail 'That is not an X9 install token. Request one from the machine registration endpoint.'
  printf '%s\n' "$token" | "$dir/x9d" -api "$x9_api" -state "$state" -models-report=false -enroll-stdin ||
    fail 'Registration did not finish. Check the message above. An expired token must be replaced.'
  unset token
fi
systemctl daemon-reload
check_effective_unit
restore_files=0
if ! systemctl start x9d.service; then
  systemctl stop x9d.service || true
  fail 'The daemon did not confirm runtime and network isolation. Read sudo journalctl -u x9d.service -b -n 80, fix the cause and run the installer again. Your saved registration can be reused.'
fi
systemctl enable x9d.service
printf 'X9 is installed. GPU compute, container runtime and network isolation checks passed. Set your price and list your GPUs separately.\n'
