#!/bin/sh
# Helm Node public installer. Generated with immutable image references.
# Read or download this script before running it. Never run it with shell tracing.
set -eu

fail() { printf 'Helm Node: %s\n' "$*" >&2; exit 1; }
add_device_group() {
  case " $model_group $device_groups " in
    *" $1 "*) ;;
    *) device_groups="$device_groups $1";;
  esac
}
usage() {
  cat <<'HELP'
Usage: sh install.sh [--backend auto|cuda|vulkan|sycl] [--network local|all|wildcard|IP,IP] [--directory PATH] [--models-directory PATH] [--port PORT] [--prepare-only] [--fleet-setup | --terminal-admin]
  auto     Detect GPU vendors/drivers; choose one runtime if several are available (default)
  cuda     NVIDIA GPU with its driver and NVIDIA Container Toolkit
  vulkan   AMD GPU with host DRM drivers (/dev/dri)
  sycl     Intel GPU with host DRM drivers (/dev/dri)
Requires Linux AMD64 or ARM64, local Docker Engine, and Docker Compose 2.30 or newer.
ARM64 currently supports CUDA; the Intel SYCL and AMD Vulkan recipes require AMD64.
Environment: prod. UAT: /srv/apps/helm-node-uat, port 13011. Production: /srv/apps/helm-node, port 13010.
The directory must not already exist. UAT models stay inside the UAT directory; production defaults to /srv/models.
Run with permission to create these directories, or choose writable paths explicitly.
First-time setup opens in your browser: start locally or join Fleet.
--fleet-setup is a compatibility alias for browser setup.
--terminal-admin uses interactive terminal login/password setup instead; Fleet can be connected later in Settings.
On a remote/headless host, a private clickable setup link is shown only in an interactive terminal.
Select local-only, individual LAN/VPN addresses, all detected addresses, or wildcard access.
Without a terminal, networking defaults to local-only; use --network for unattended selection.
An SSH tunnel is needed for remote local-only access. No setup key needs to be typed.
Remote bindings use HTTP: use a trusted LAN/VPN or an HTTPS reverse proxy.
No drivers, Docker, models, TLS certificates or firewall rules are installed.
HELP
}

# Embedded by build.py. Host discovery never installs drivers or changes networking.
has_terminal() { ( : </dev/tty ) 2>/dev/null; }

detect_gpus() {
  gpu_candidates=
  gpu_inventory=
  printf '\nDetected graphics hardware:\n'
  for gpu_path in /sys/bus/pci/devices/*; do
    [ -r "$gpu_path/class" ] && [ -r "$gpu_path/vendor" ] || continue
    case "$(cat "$gpu_path/class")" in 0x03*) ;; *) continue;; esac
    gpu_slot=${gpu_path##*/}
    case "$(cat "$gpu_path/vendor")" in
      0x10de) gpu_vendor=NVIDIA; gpu_backend=cuda;;
      0x8086) gpu_vendor=Intel; gpu_backend=sycl;;
      0x1002) gpu_vendor=AMD; gpu_backend=vulkan;;
      *) gpu_vendor=Other; gpu_backend=unsupported;;
    esac
    gpu_label="$gpu_vendor GPU at $gpu_slot"
    if command -v lspci >/dev/null 2>&1; then
      gpu_label=$(lspci -D -s "$gpu_slot" 2>/dev/null) || gpu_label="$gpu_vendor GPU at $gpu_slot"
    fi
    gpu_status='host driver missing'
    if [ -d "$gpu_path/driver" ]; then
      gpu_status='host driver present; container access not yet tested'
      case "$gpu_backend:$architecture" in
        sycl:amd64|vulkan:amd64)
          case " $gpu_candidates " in *" $gpu_backend "*) ;; *) gpu_candidates="$gpu_candidates $gpu_backend";; esac;;
      esac
    fi
    case "$gpu_backend:$architecture" in
      sycl:arm64|vulkan:arm64) gpu_status='no supported ARM64 runtime recipe';;
      unsupported:*) gpu_status='no supported runtime recipe';;
    esac
    printf '  %s — %s\n' "$gpu_label" "$gpu_status"
    gpu_inventory="$gpu_inventory$gpu_vendor|$gpu_slot|$gpu_backend|$gpu_status
"
  done
  # Also covers hosts where the PCI inventory is unavailable but NVIDIA works.
  nvidia_devices=
  if command -v nvidia-smi >/dev/null 2>&1; then
    nvidia_devices=$(nvidia-smi -L 2>/dev/null) || nvidia_devices=
  fi
  if [ -n "$nvidia_devices" ]; then
    printf '  %s\n' "$nvidia_devices"
    gpu_candidates="cuda$gpu_candidates"
    gpu_inventory="$gpu_inventory$nvidia_devices
"
  fi
  [ -n "$gpu_inventory$nvidia_devices" ] || printf '  No supported graphics hardware detected.\n'
}

select_backend() {
  detect_gpus
  [ "$backend" = auto ] || return 0
  # Candidate words are fixed recipe identifiers, never device-provided strings.
  set -- $gpu_candidates
  case "$#" in
    0) fail 'No usable GPU backend detected. Check host drivers, or use --backend cuda|sycl|vulkan for an explicit recipe. No files were created.';;
    1) backend=$1; printf 'Selected %s automatically; a container GPU probe will verify it.\n' "$backend";;
    *)
      printf 'Multiple GPU backends detected: %s\n' "$gpu_candidates"
      printf '%s\n' 'This release installs one runtime. Other GPU families will not be enabled by this installation.'
      has_terminal || fail 'Choose one detected runtime with --backend cuda|sycl|vulkan. Mixed-runtime execution is not supported yet.'
      while :; do
        printf 'Runtime to install (%s): ' "$gpu_candidates" >/dev/tty
        IFS= read -r backend </dev/tty || fail 'Runtime selection cancelled.'
        case " $gpu_candidates " in *" $backend "*) [ -n "$backend" ] && break;; esac
        printf 'Choose one of:%s\n' "$gpu_candidates"
      done;;
  esac
}

detect_networks() {
  network_rows=
  if command -v ip >/dev/null 2>&1; then
    network_raw=$(ip -o addr show up) || fail 'Could not inspect host interfaces with ip.'
    network_rows=$(printf '%s\n' "$network_raw" | awk '
      $3 == "inet" || $3 == "inet6" {
        iface=$2; sub(/@.*/, "", iface)
        if (iface == "lo" || iface ~ /^(docker|veth|virbr)/ || iface ~ /^br-[0-9a-f]+$/) next
        if ($0 !~ /scope global/ || $0 ~ /tentative|dadfailed|deprecated/) next
        address=$4; sub(/\/.*/, "", address)
        if (address !~ /^[0-9a-fA-F:.]+$/ || seen[address]++) next
        print iface "|" address
      }')
  else
    printf '%s\n' 'Interface discovery unavailable: install iproute2 to select LAN/VPN addresses.'
  fi
  printf '\nAvailable network addresses (remote reachability is not yet tested):\n  localhost: 127.0.0.1\n'
  printf '%s\n' "$network_rows" | while IFS='|' read -r network_iface network_address; do
    [ -n "$network_address" ] || continue
    printf '  %s: %s\n' "$network_iface" "$network_address"
  done
}

add_binding() {
  case " $bindings " in *" $1 "*) ;; *) bindings="$bindings $1";; esac
}

select_networks() {
  detect_networks
  if [ -z "$network_choice" ]; then
    if has_terminal; then
      printf '%s\n' 'Choose local, all detected addresses, a comma-separated address list, or wildcard (all interfaces, including future ones).'
      printf 'Network access [local]: ' >/dev/tty
      IFS= read -r network_choice </dev/tty || fail 'Network selection cancelled.'
    fi
    network_choice=${network_choice:-local}
  fi
  bindings=127.0.0.1
  case "$network_choice" in
    local) ;;
    all)
      [ -n "$network_rows" ] || fail 'No LAN/VPN addresses detected. Use --network local or install iproute2 and check interface state.'
      for network_address in $(printf '%s\n' "$network_rows" | cut -d '|' -f 2); do add_binding "$network_address"; done;;
    wildcard)
      bindings=0.0.0.0
      case "$network_rows" in *:*) bindings="$bindings ::";; esac
      printf '%s\n' 'Wildcard access includes public and future interfaces. IPv6 is included when a usable IPv6 address was detected.';;
    *)
      case "$network_choice" in *[!0-9a-fA-F:.,]*|,*|*,|*,,*) fail 'Network selection must be local, all, wildcard, or a comma-separated list of detected IP addresses.';; esac
      for network_address in $(printf '%s' "$network_choice" | tr ',' ' '); do
        [ "$network_address" != 127.0.0.1 ] || continue
        printf '%s\n' "$network_rows" | cut -d '|' -f 2 | grep -Fxq -- "$network_address" || fail "Address not available on an eligible active host interface: $network_address"
        add_binding "$network_address"
      done;;
  esac
  # Prefer a selected remote address for SSH setup; a desktop stays on localhost.
  setup_address=127.0.0.1
  if [ -n "${SSH_CONNECTION:-}${SSH_TTY:-}" ] || [ -z "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; then
    for network_address in $bindings; do
      case "$network_address" in 127.0.0.1|0.0.0.0|::) continue;; esac
      setup_address=$network_address; break
    done
    if [ "$network_choice" = wildcard ] && [ -n "$network_rows" ]; then
      setup_address=$(printf '%s\n' "$network_rows" | head -n 1 | cut -d '|' -f 2)
    fi
  fi
  case "$setup_address" in *:*) setup_host="[$setup_address]";; *) setup_host=$setup_address;; esac
  setup_url="http://$setup_host:$port"
  if [ "$bindings" != 127.0.0.1 ]; then
    printf '%s\n' 'Selected remote access uses HTTP. Use a trusted LAN/VPN or an HTTPS reverse proxy; no TLS certificates or firewall rules are installed.'
  fi
}

write_ports() {
  for network_address in ${bindings:-127.0.0.1}; do
    case "$network_address" in *:*) network_host="[$network_address]";; *) network_host=$network_address;; esac
    printf '      - "%s:${PORT:-13010}:3000"\n' "$network_host"
  done
}

check_ports() {
  # Docker can publish without a listening userspace proxy, so inspect it too.
  published=$(docker ps --filter "publish=$port" --format '{{.Names}}') || fail 'Could not check Docker port publications.'
  [ -z "$published" ] || fail "Port $port is already published by Docker: $published. Choose another --port or stop the intended old service."
  if command -v ss >/dev/null 2>&1; then
    listening=$(ss -H -ltn) || fail 'Could not check listening TCP ports.'
    for network_endpoint in $(printf '%s\n' "$listening" | awk '{print $4}'); do
      [ "${network_endpoint##*:}" = "$port" ] || continue
      network_listener=${network_endpoint%:*}
      network_listener=$(printf '%s' "$network_listener" | tr -d '[]')
      case "$network_listener" in '*'|0.0.0.0|::) fail "Port $port already has a wildcard listener.";; esac
      case " $bindings " in *" $network_listener "*|*" 0.0.0.0 "*|*" :: "*) fail "Port $port is already listening at $network_listener.";; esac
    done
  else
    printf '%s\n' 'TCP listener precheck unavailable (ss missing); Docker will validate bindings at startup.'
  fi
}

print_access_urls() {
  printf '\nConfigured access URLs:\n'
  access_addresses=$bindings
  if [ "$network_choice" = wildcard ]; then
    access_addresses="127.0.0.1 $(printf '%s\n' "$network_rows" | cut -d '|' -f 2)"
  fi
  for network_address in $access_addresses; do
    case "$network_address" in *:*) network_host="[$network_address]";; *) network_host=$network_address;; esac
    printf '  http://%s:%s\n' "$network_host" "$port"
  done
  printf '%s\n' 'Remote reachability depends on client routing, VPN access and firewall rules; test these URLs from your computer.'
}


write_compose() {
  case "$backend" in
    cuda)
      cat <<'HELM_COMPOSE'
name: ${COMPOSE_PROJECT_NAME:?Missing project name}
services:
  helm-runtime-installer:
    platform: ${LOCAL_SERVICE_PLATFORM:?Missing host platform}
    image: ghcr.io/ggml-org/llama.cpp@sha256:6ac921528d613deb0fd142c654735e594a446a1c37a069eeab08d8fd974d4bec
    restart: "no"
    entrypoint:
      - /bin/sh
      - -ec
      - |
        runtime_source="$${RUNTIME_SOURCE_DIR:-/app}"
        rm -rf /runtime/*
        mkdir -p /runtime/app /runtime/libs
        cp -a "$$runtime_source"/. /runtime/app/
        mkdir -p /runtime/rootfs
        for support_pattern in $${RUNTIME_EXTRA_PATHS:-}; do
          for support_path in $$support_pattern; do
            [ -e "$$support_path" ] || continue
            mkdir -p "/runtime/rootfs$$(dirname "$$support_path")"
            cp -a "$$support_path" "/runtime/rootfs$$support_path"
          done
        done
        {
          ldd /runtime/app/llama-server 2>/dev/null || true
          find /runtime/app -maxdepth 1 -type f -name '*.so*' -exec ldd {} \; 2>/dev/null || true
        } | awk '/=> \/|^[[:space:]]*\// { for (i = 1; i <= NF; i++) if ($$i ~ /^\//) print $$i }' | grep -Ev '/(ld-linux|libc|libpthread|libdl|librt|libm)\.so' | sort -u | while read -r lib; do
          cp -L "$$lib" /runtime/libs/ 2>/dev/null || true
        done
        test -x /runtime/app/llama-server
    environment:
      RUNTIME_SOURCE_DIR: ${LOCAL_SERVICE_RUNTIME_SOURCE:-/app}
      RUNTIME_EXTRA_PATHS: ${LOCAL_SERVICE_RUNTIME_EXTRA_PATHS:-}
    volumes:
      - runtime_app:/runtime
  helm-node:
    platform: ${LOCAL_SERVICE_PLATFORM:?Missing host platform}
    image: ghcr.io/accoladesolutions/helm-node@sha256:d2b82b11f2ce7f4d5b529bd7f799fc5bb8244e2b8bc16229f162b3200fd93476
    container_name: ${COMPOSE_PROJECT_NAME:-helm-node}
    init: true
    restart: unless-stopped
    stop_grace_period: 30s
    depends_on:
      helm-runtime-installer:
        condition: service_completed_successfully
    ports:
HELM_COMPOSE
      write_ports
      cat <<'HELM_COMPOSE'
    environment:
      LOCAL_SERVICE_IMAGE: ghcr.io/accoladesolutions/helm-node@sha256:d2b82b11f2ce7f4d5b529bd7f799fc5bb8244e2b8bc16229f162b3200fd93476
      LOCAL_SERVICE_RUNTIME_IMAGE: ghcr.io/ggml-org/llama.cpp@sha256:6ac921528d613deb0fd142c654735e594a446a1c37a069eeab08d8fd974d4bec
      LOCAL_SERVICE_FLEET_SETUP: ${LOCAL_SERVICE_FLEET_SETUP:-}
      LOCAL_SERVICE_SETUP_TOKEN: ${LOCAL_SERVICE_SETUP_TOKEN:?Missing setup token}
      LOCAL_SERVICE_ORIGINS: ${LOCAL_SERVICE_ORIGINS:-}
      LOCAL_SERVICE_INFERENCE_ORIGINS: ${LOCAL_SERVICE_INFERENCE_ORIGINS:-}
      LOCAL_SERVICE_TRANSFER_TOKEN: ${LOCAL_SERVICE_TRANSFER_TOKEN:-}
      LOCAL_SERVICE_NODE_NAME: ${LOCAL_SERVICE_NODE_NAME:-}
      LOCAL_SERVICE_RUNTIME: ${LOCAL_SERVICE_RUNTIME:-/runtime/app/llama-server}
      LOCAL_SERVICE_RUNTIME_LIBRARY_PATH: ${LOCAL_SERVICE_RUNTIME_LIBRARY_PATH:-/runtime/app:/runtime/libs}
      LOCAL_SERVICE_RUNTIME_LIBRARY_ROOTS: ${LOCAL_SERVICE_RUNTIME_LIBRARY_ROOTS:-}
      NVIDIA_VISIBLE_DEVICES: ${NVIDIA_VISIBLE_DEVICES:-all}
      NVIDIA_DRIVER_CAPABILITIES: ${NVIDIA_DRIVER_CAPABILITIES:-compute,utility}
    gpus: all
    group_add:
      - "${MODEL_GROUP_ID:-1000}"
HELM_COMPOSE
      for group in $device_groups; do printf '      - "%s"\n' "$group"; done
      cat <<'HELM_COMPOSE'
    volumes:
      - ./config:/config
      - runtime_app:/runtime:ro
      - ${MODEL_DIRECTORY:-/srv/models}:/models:${MODEL_MOUNT_MODE:-ro}
      - ${IMPORT_DIRECTORY:-/srv/models}:/import:ro
    read_only: true
    tmpfs:
      - /tmp:size=256m
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
volumes:
  runtime_app:
HELM_COMPOSE
      ;;
    vulkan)
      cat <<'HELM_COMPOSE'
name: ${COMPOSE_PROJECT_NAME:?Missing project name}
services:
  helm-runtime-installer:
    platform: ${LOCAL_SERVICE_PLATFORM:?Missing host platform}
    # This recipe installs the AMD RADV driver and x86-64 loader.
    image: ghcr.io/ggml-org/llama.cpp@sha256:819d7a7e313f50e5313f87968710adb270b6714db0de27d9a729597819410ad4
    restart: "no"
    entrypoint:
      - /bin/sh
      - -ec
      - |
        # AMD64 runtime libraries and their matching loader stay isolated from Node.
        test -x /app/llama-server
        test -f /usr/share/vulkan/icd.d/radeon_icd.json
        rm -rf /runtime/app /runtime/bin /runtime/libs /runtime/share
        mkdir -p /runtime/app /runtime/bin /runtime/libs /runtime/share
        cp -a /app/. /runtime/bin/
        cp -a /usr/lib/x86_64-linux-gnu/. /runtime/libs/
        cp -L /lib64/ld-linux-x86-64.so.2 /runtime/ld-linux-x86-64.so.2
        cp /usr/share/vulkan/icd.d/radeon_icd.json /runtime/share/radeon_icd.json
        sed -i 's|"libvulkan_radeon.so"|"/runtime/libs/libvulkan_radeon.so"|' /runtime/share/radeon_icd.json
        cat > /runtime/app/llama-server <<'LAUNCHER'
        #!/bin/sh
        export VK_DRIVER_FILES=/runtime/share/radeon_icd.json
        export LD_LIBRARY_PATH=/runtime/bin:/runtime/libs
        export XDG_CACHE_HOME=/tmp/llama-cache
        # Backend plugins search the working directory when using an explicit loader.
        cd /runtime/bin
        exec /runtime/ld-linux-x86-64.so.2 --library-path /runtime/bin:/runtime/libs /runtime/bin/llama-server "$$@"
        LAUNCHER
        chmod 0755 /runtime/app/llama-server
    volumes:
      - runtime_app:/runtime
  helm-node:
    platform: ${LOCAL_SERVICE_PLATFORM:?Missing host platform}
    image: ghcr.io/accoladesolutions/helm-node@sha256:d2b82b11f2ce7f4d5b529bd7f799fc5bb8244e2b8bc16229f162b3200fd93476
    container_name: ${COMPOSE_PROJECT_NAME:-helm-node}
    init: true
    restart: unless-stopped
    stop_grace_period: 30s
    depends_on:
      helm-runtime-installer:
        condition: service_completed_successfully
    ports:
HELM_COMPOSE
      write_ports
      cat <<'HELM_COMPOSE'
    environment:
      LOCAL_SERVICE_IMAGE: ghcr.io/accoladesolutions/helm-node@sha256:d2b82b11f2ce7f4d5b529bd7f799fc5bb8244e2b8bc16229f162b3200fd93476
      LOCAL_SERVICE_RUNTIME_IMAGE: ghcr.io/ggml-org/llama.cpp@sha256:819d7a7e313f50e5313f87968710adb270b6714db0de27d9a729597819410ad4
      LOCAL_SERVICE_FLEET_SETUP: ${LOCAL_SERVICE_FLEET_SETUP:-}
      LOCAL_SERVICE_SETUP_TOKEN: ${LOCAL_SERVICE_SETUP_TOKEN:?Missing setup token}
      LOCAL_SERVICE_ORIGINS: ${LOCAL_SERVICE_ORIGINS:-}
      LOCAL_SERVICE_INFERENCE_ORIGINS: ${LOCAL_SERVICE_INFERENCE_ORIGINS:-}
      LOCAL_SERVICE_TRANSFER_TOKEN: ${LOCAL_SERVICE_TRANSFER_TOKEN:-}
      LOCAL_SERVICE_NODE_NAME: ${LOCAL_SERVICE_NODE_NAME:-}
      LOCAL_SERVICE_RUNTIME: /runtime/app/llama-server
      # The wrapper selects the runtime's libc; do not apply it to /bin/sh or Node.
      LOCAL_SERVICE_RUNTIME_LIBRARY_PATH: /runtime/app
    devices:
      - /dev/dri:/dev/dri
    group_add:
      - "${MODEL_GROUP_ID:-1000}"
HELM_COMPOSE
      for group in $device_groups; do printf '      - "%s"\n' "$group"; done
      cat <<'HELM_COMPOSE'
    volumes:
      - ./config:/config
      - runtime_app:/runtime:ro
      - ${MODEL_DIRECTORY:-/srv/models}:/models:${MODEL_MOUNT_MODE:-ro}
      - ${IMPORT_DIRECTORY:-/srv/models}:/import:ro
    read_only: true
    tmpfs:
      - /tmp:size=256m
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
volumes:
  runtime_app:
HELM_COMPOSE
      ;;
    sycl)
      cat <<'HELM_COMPOSE'
name: ${COMPOSE_PROJECT_NAME:?Missing project name}
services:
  helm-runtime-installer:
    platform: ${LOCAL_SERVICE_PLATFORM:?Missing host platform}
    image: ghcr.io/accoladesolutions/helm-runtime@sha256:baafcb1e6455f1f14808e02e1bae7f28f7b687b03715036107c7e7a6b04048f6
    restart: "no"
    entrypoint:
      - /bin/sh
      - -ec
      - |
        runtime_source="$${RUNTIME_SOURCE_DIR:-/app}"
        rm -rf /runtime/* /runtime-opt-intel/* /runtime-opencl/* /runtime-usr-lib/* /runtime-intel-opencl/* /runtime-local-lib/*
        mkdir -p /runtime/app /runtime/libs /runtime-opt-intel /runtime-opencl /runtime-usr-lib /runtime-intel-opencl /runtime-local-lib
        cp -a "$$runtime_source"/. /runtime/app/
        cp -a /opt/intel/. /runtime-opt-intel/
        cp -a /etc/OpenCL/. /runtime-opencl/
        cp -a /usr/lib/x86_64-linux-gnu/intel-opencl/. /runtime-intel-opencl/ 2>/dev/null || true
        cp -a /usr/lib/x86_64-linux-gnu/libze* /usr/lib/x86_64-linux-gnu/libigdgmm* /usr/lib/x86_64-linux-gnu/libdrm_intel* /runtime-usr-lib/ 2>/dev/null || true
        cp -a /usr/local/lib/. /runtime-local-lib/ 2>/dev/null || true
        for support_pattern in $${RUNTIME_EXTRA_PATHS:-}; do
          for support_path in $$support_pattern; do
            [ -e "$$support_path" ] || continue
            mkdir -p "/runtime/rootfs$$(dirname "$$support_path")"
            cp -a "$$support_path" "/runtime/rootfs$$support_path"
          done
        done
        {
          ldd /runtime/app/llama-server 2>/dev/null || true
          find /runtime/app -maxdepth 1 -type f -name '*.so*' -exec ldd {} \; 2>/dev/null || true
        } | awk '/=> \/|^[[:space:]]*\// { for (i = 1; i <= NF; i++) if ($$i ~ /^\//) print $$i }' | grep -Ev '/(ld-linux|libc|libpthread|libdl|librt|libm)\.so' | sort -u | while read -r lib; do
          cp -L "$$lib" /runtime/libs/ 2>/dev/null || true
        done
        test -x /runtime/app/llama-server
    environment:
      RUNTIME_SOURCE_DIR: ${LOCAL_SERVICE_RUNTIME_SOURCE:-/app}
      RUNTIME_EXTRA_PATHS: ${LOCAL_SERVICE_RUNTIME_EXTRA_PATHS:-/usr/share/vulkan/icd.d/intel*.json}
    volumes:
      - runtime_app:/runtime
      - runtime_opt_intel:/runtime-opt-intel
      - runtime_opencl:/runtime-opencl
      - runtime_usr_lib:/runtime-usr-lib
      - runtime_intel_opencl:/runtime-intel-opencl
      - runtime_local_lib:/runtime-local-lib
  helm-node:
    platform: ${LOCAL_SERVICE_PLATFORM:?Missing host platform}
    image: ghcr.io/accoladesolutions/helm-node@sha256:d2b82b11f2ce7f4d5b529bd7f799fc5bb8244e2b8bc16229f162b3200fd93476
    container_name: ${COMPOSE_PROJECT_NAME:-helm-node}
    init: true
    restart: unless-stopped
    stop_grace_period: 30s
    depends_on:
      helm-runtime-installer:
        condition: service_completed_successfully
    ports:
HELM_COMPOSE
      write_ports
      cat <<'HELM_COMPOSE'
    environment:
      LOCAL_SERVICE_IMAGE: ghcr.io/accoladesolutions/helm-node@sha256:d2b82b11f2ce7f4d5b529bd7f799fc5bb8244e2b8bc16229f162b3200fd93476
      LOCAL_SERVICE_RUNTIME_IMAGE: ghcr.io/accoladesolutions/helm-runtime@sha256:baafcb1e6455f1f14808e02e1bae7f28f7b687b03715036107c7e7a6b04048f6
      LOCAL_SERVICE_FLEET_SETUP: ${LOCAL_SERVICE_FLEET_SETUP:-}
      LOCAL_SERVICE_SETUP_TOKEN: ${LOCAL_SERVICE_SETUP_TOKEN:?Missing setup token}
      LOCAL_SERVICE_ORIGINS: ${LOCAL_SERVICE_ORIGINS:-}
      LOCAL_SERVICE_INFERENCE_ORIGINS: ${LOCAL_SERVICE_INFERENCE_ORIGINS:-}
      LOCAL_SERVICE_TRANSFER_TOKEN: ${LOCAL_SERVICE_TRANSFER_TOKEN:-}
      LOCAL_SERVICE_NODE_NAME: ${LOCAL_SERVICE_NODE_NAME:-}
      LOCAL_SERVICE_RUNTIME: ${LOCAL_SERVICE_RUNTIME:-/runtime/app/llama-server}
      LOCAL_SERVICE_RUNTIME_LIBRARY_PATH: ${LOCAL_SERVICE_RUNTIME_LIBRARY_PATH:-/runtime/app:/runtime/libs:/runtime-usr-lib:/usr/local/lib:/opt/intel/oneapi/compiler/2025.3/lib:/opt/intel/oneapi/2025.3/lib}
      LOCAL_SERVICE_RUNTIME_LIBRARY_ROOTS: ${LOCAL_SERVICE_RUNTIME_LIBRARY_ROOTS:-/opt/intel,/runtime-usr-lib,/usr/local/lib,/usr/lib/x86_64-linux-gnu/intel-opencl}
      LOCAL_SERVICE_RUNTIME_ENV_ONEAPI_ROOT: ${LOCAL_SERVICE_RUNTIME_ENV_ONEAPI_ROOT:-/opt/intel/oneapi}
      LOCAL_SERVICE_RUNTIME_ENV_OCL_ICD_FILENAMES: ${LOCAL_SERVICE_RUNTIME_ENV_OCL_ICD_FILENAMES:-/opt/intel/oneapi/compiler/2025.3/lib/libintelocl.so}
      LOCAL_SERVICE_RUNTIME_ENV_INTEL_PYTHONHOME: ${LOCAL_SERVICE_RUNTIME_ENV_INTEL_PYTHONHOME:-/opt/intel/oneapi/debugger/2025.3/opt/debugger}
    devices:
      - /dev/dri:/dev/dri
    group_add:
      - "${MODEL_GROUP_ID:-1000}"
HELM_COMPOSE
      for group in $device_groups; do printf '      - "%s"\n' "$group"; done
      cat <<'HELM_COMPOSE'
    volumes:
      - ./config:/config
      - runtime_app:/runtime:ro
      - runtime_opt_intel:/opt/intel:ro
      - runtime_opencl:/etc/OpenCL:ro
      - runtime_usr_lib:/runtime-usr-lib:ro
      - runtime_intel_opencl:/usr/lib/x86_64-linux-gnu/intel-opencl:ro
      - runtime_local_lib:/usr/local/lib:ro
      - ${MODEL_DIRECTORY:-/srv/models}:/models:${MODEL_MOUNT_MODE:-ro}
      - ${IMPORT_DIRECTORY:-/srv/models}:/import:ro
    read_only: true
    tmpfs:
      - /tmp:size=256m
    cap_drop: [ALL]
    security_opt: ["no-new-privileges:true"]
volumes:
  runtime_app:
  runtime_opt_intel:
  runtime_opencl:
  runtime_usr_lib:
  runtime_intel_opencl:
  runtime_local_lib:
HELM_COMPOSE
      ;;

  esac
}

# The launch document is private, outside the served public directory. Passing its
# path to the desktop opener avoids putting the setup key in process arguments.
write_first_start() {
  cat > "$directory/first-start.html" <<EOF
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="referrer" content="no-referrer"><meta http-equiv="refresh" content="0;url=$setup_url/#setup=$setup_token"><title>Helm Node setup</title></head><body><p><a href="$setup_url/#setup=$setup_token" rel="noreferrer">Continue to Helm Node setup</a></p></body></html>
EOF
}

open_first_start() {
  # Never open a browser as root, in an SSH/X-forwarded desktop, or before health
  # checks pass. Remote shells cannot launch the customer's local browser.
  if [ "$(id -u)" != 0 ] && [ -z "${SSH_CONNECTION:-}${SSH_TTY:-}" ] &&
     [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ] && command -v xdg-open >/dev/null 2>&1; then
    if xdg-open "$directory/first-start.html" >/dev/null 2>&1; then
      printf '%s\n' 'Opened first-time setup. Choose Start locally or Join Fleet; your setup key is already supplied.'
      return
    fi
  fi
  # Keep bearer proof out of redirected stdout/stderr and CI/install logs.
  if ( : >/dev/tty ) 2>/dev/null; then
    printf '\nOpen this private link to choose local or Fleet setup (key included):\n%s/#setup=%s\nKeep this link private. Localhost links need an SSH tunnel when opened from another computer.\n' "$setup_url" "$setup_token" >/dev/tty
  else
    printf 'Browser unavailable. A private launch document is saved at %s/first-start.html. Open it on your computer with access to this Node through localhost or an SSH tunnel.\n' "$directory"
  fi
}

main() {
  environment=prod
  backend=auto network_choice= directory= models_directory= port= prepare_only=false fleet_setup= setup_mode=
  project_name=helm-node
  [ "$environment" != uat ] || project_name=helm-node-uat
  while [ "$#" -gt 0 ]; do
    case "$1" in
      --backend|--network|--directory|--models-directory|--port)
        [ "$#" -ge 2 ] || fail "Missing value for $1"
        case "$1" in
          --backend) backend=$2;;
          --network) [ -n "$2" ] || fail 'Network selection cannot be empty.'; network_choice=$2;;
          --directory) directory=$2;;
          --models-directory) models_directory=$2;;
          --port) port=$2;;
        esac
        shift 2;;
      --prepare-only) prepare_only=true; shift;;
      --fleet-setup)
        [ "$setup_mode" != terminal ] || fail 'Choose either browser setup or --terminal-admin.'
        setup_mode=browser; shift;;
      --terminal-admin)
        [ "$setup_mode" != browser ] || fail 'Choose either browser setup or --terminal-admin.'
        setup_mode=terminal; shift;;
      --help|-h) usage; return;;
      *) usage >&2; fail "Unknown option: $1";;
    esac
  done
  directory=${directory:-/srv/apps/$project_name}
  if [ "$environment" = uat ]; then
    port=${port:-13011}; models_directory=${models_directory:-$directory/models}
  else
    port=${port:-13010}; models_directory=${models_directory:-/srv/models}
  fi
  setup_mode=${setup_mode:-browser}
  fleet_setup=$environment
  case "$backend" in auto|cuda|vulkan|sycl) ;; *) usage >&2; fail 'Choose --backend auto, cuda, vulkan or sycl.';; esac
  case "$port" in ''|*[!0-9]*|0*) fail 'Port must be an integer from 1024 to 65535.';; esac
  [ "${#port}" -le 5 ] && [ "$port" -ge 1024 ] && [ "$port" -le 65535 ] || fail 'Port must be between 1024 and 65535.'
  case "$directory" in /*) ;; *) directory="$PWD/$directory";; esac
  case "$directory" in *[!a-zA-Z0-9_./\ -]*) fail 'Application directory supports letters, numbers, spaces, /, ., _, and -.';; esac
  case "$models_directory" in /*) ;; *) models_directory="$PWD/$models_directory";; esac
  case "$models_directory" in *[!a-zA-Z0-9_./\ -]*) fail 'Model directory supports letters, numbers, spaces, /, ., _, and -.';; esac
  [ ! -e "$models_directory" ] || [ -d "$models_directory" ] || fail 'Model storage must be a directory.'
  [ ! -L "$models_directory" ] || [ -d "$models_directory" ] || fail 'Model storage symlink is broken.'
  [ ! -e "$directory" ] && [ ! -L "$directory" ] || fail "Directory already exists; it will not be overwritten: $directory"
  [ "$(uname -s)" = Linux ] || fail 'This GPU installer requires Linux AMD64 or ARM64.'
  case "$(uname -m)" in
    x86_64|amd64) architecture=amd64;;
    aarch64|arm64) architecture=arm64;;
    *) fail 'This GPU installer requires Linux AMD64 or ARM64.';;
  esac
  [ "$architecture" != arm64 ] || [ "$backend" = cuda ] || [ "$backend" = auto ] || fail 'ARM64 currently supports --backend cuda only; SYCL and Vulkan recipes require AMD64.'
  for utility in docker od tr id stat dirname; do command -v "$utility" >/dev/null 2>&1 || fail "Required command is missing: $utility"; done
  docker_endpoint=${DOCKER_HOST:-$(docker context inspect --format '{{.Endpoints.docker.Host}}')}
  case "$docker_endpoint" in unix://*) ;; *) fail 'Use a local Docker Engine (Unix socket), not a remote Docker context.';; esac
  server_platform=$(docker info --format '{{.OSType}}/{{.Architecture}}') || fail 'Docker Engine is unavailable. Check the daemon and your Docker permissions.'
  case "$server_platform" in
    linux/x86_64|linux/amd64) docker_architecture=amd64;;
    linux/aarch64|linux/arm64) docker_architecture=arm64;;
    *) fail "Unsupported Docker host: $server_platform";;
  esac
  [ "$docker_architecture" = "$architecture" ] || fail 'Docker architecture does not match this host; emulated or remote installations are not supported.'
  compose_version=$(docker compose version --short) || fail 'Install the Docker Compose plugin (2.30 or newer).'
  compose_version=${compose_version#v}
  major=${compose_version%%.*}; rest=${compose_version#*.}; minor=${rest%%.*}
  case "$major:$minor" in *[!0-9:]*|:|*:) fail 'Cannot determine Docker Compose version.';; esac
  { [ "$major" -eq 2 ] && [ "$minor" -ge 30 ]; } || [ "$major" -gt 2 ] || fail 'Docker Compose 2.30 or newer is required.'
  select_backend
  select_networks
  check_ports
  model_group=$(id -g)
  device_groups=
  case "$backend" in
    cuda)
      command -v nvidia-smi >/dev/null 2>&1 && nvidia-smi -L >/dev/null 2>&1 || fail 'Install a working NVIDIA driver and NVIDIA Container Toolkit first.';;
    vulkan|sycl)
      [ -d /dev/dri ] || fail 'No /dev/dri devices found. Install the GPU host driver first.'
      found_render=false
      for device in /dev/dri/renderD* /dev/dri/card*; do
        [ -c "$device" ] || continue
        case "$device" in */renderD*) found_render=true;; esac
        add_device_group "$(stat -c '%g' "$device")"
      done
      [ "$found_render" = true ] || fail 'No GPU render device found under /dev/dri.';;
  esac
  existing_project=$(docker ps -aq --filter "label=com.docker.compose.project=$project_name") || fail "Cannot check existing containers."
  [ -z "$existing_project" ] || fail "Compose project $project_name already exists; use its saved installation directory."
  umask 077
  mkdir -p -- "$(dirname -- "$directory")" || fail 'Cannot create the application parent directory. Use an account with write access or --directory.'
  mkdir -- "$directory" || fail 'Cannot create the install directory.'
  directory=$(CDPATH= cd -- "$directory" && pwd -P)
  mkdir -- "$directory/config"
  chmod 2770 "$directory/config"
  if [ ! -d "$models_directory" ]; then
    mkdir -p -- "$models_directory" || fail 'Cannot create model storage. Use an account with write access or --models-directory.'
    chmod 2770 "$models_directory"
  fi
  # Shared model storage keeps its existing owner/mode; add its real numeric group.
  all_groups="$device_groups $(id -g)"
  model_group=$(stat -L -c '%g' "$models_directory")
  # Config belongs to the installing user; shared models can have another group.
  add_device_group "$(id -g)"
  device_groups=
  for group in $all_groups; do add_device_group "$group"; done
  setup_token=$(od -An -N24 -tx1 /dev/urandom | tr -d ' \n')
  [ "${#setup_token}" -eq 48 ] || fail 'Could not generate the setup token.'
  cat > "$directory/.env" <<EOF
COMPOSE_PROJECT_NAME=$project_name
LOCAL_SERVICE_PLATFORM=linux/$architecture
PORT=$port
MODEL_GROUP_ID=$model_group
MODEL_DIRECTORY='$models_directory'
IMPORT_DIRECTORY='$models_directory'
MODEL_MOUNT_MODE=rw
LOCAL_SERVICE_SETUP_TOKEN=$setup_token
LOCAL_SERVICE_FLEET_SETUP=$fleet_setup
EOF
  # No secrets here; these choices describe this installation, not global defaults.
  cat > "$directory/installation.txt" <<EOF
environment=$environment
platform=linux/$architecture
backend=$backend
network=$network_choice
bindings=$bindings
port=$port
setup_url=$setup_url
EOF
  printf '%s\n' "$gpu_inventory" > "$directory/detected-gpus.txt"
  printf '%s\n' "$network_rows" > "$directory/detected-networks.txt"
  write_compose > "$directory/compose.yaml"
  [ "$setup_mode" != browser ] || write_first_start
  cat > "$directory/setup-admin.sh" <<'HELM_SETUP_ADMIN'
#!/bin/sh
# Generated installer helper. Credentials are never arguments, env vars or files.
set +x
set -eu
fail() { printf 'Helm Node: %s\n' "$*" >&2; exit 1; }
directory=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
command -v stty >/dev/null 2>&1 || fail 'stty is required for hidden password entry.'
# /dev/tty also works when the installer itself was read from a pipe.
# dash exits on a failed special-builtin redirection; probe in a subshell first.
(exec 3<>/dev/tty) 2>/dev/null || fail 'An interactive terminal is required. Connect with ssh -t and run sh setup-admin.sh in the installation directory.'
exec 3<>/dev/tty
terminal_state=$(stty -g <&3)
cleanup() { stty "$terminal_state" <&3 || true; unset password confirmation; }
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
printf '\nCreate the local administrator for this Node.\n' >&3
while :; do
  printf 'Login name: ' >&3
  IFS= read -r username <&3 || fail 'Setup cancelled.'
  [ -n "$username" ] && break
  printf 'Enter a login name.\n' >&3
done
stty -echo <&3
while :; do
  printf 'Password: ' >&3
  IFS= read -r password <&3 || fail 'Setup cancelled.'
  printf '\nConfirm password: ' >&3
  IFS= read -r confirmation <&3 || fail 'Setup cancelled.'
  printf '\n' >&3
  if [ -z "$password" ]; then printf 'Password cannot be empty.\n' >&3
  elif [ "$password" != "$confirmation" ]; then printf 'Passwords do not match. Try again.\n' >&3
  else break; fi
done
stty "$terminal_state" <&3
docker_endpoint=${DOCKER_HOST:-$(docker context inspect --format '{{.Endpoints.docker.Host}}')}
case "$docker_endpoint" in unix://*) ;; *) fail 'Use a local Docker Engine (Unix socket).';; esac
# The application has not started. This temporary offline container uses the same
# immutable image, touches only /config, and has no runtime, GPU or model mounts.
printf '%s\n%s\n' "$username" "$password" | env -i PATH="$PATH" HOME="$HOME" \
  DOCKER_HOST="$docker_endpoint" DOCKER_CONFIG="${DOCKER_CONFIG:-$HOME/.docker}" \
  docker run --rm -i --network none --read-only --cap-drop ALL --security-opt no-new-privileges:true \
  --group-add "$(stat -c '%g' "$directory/config")" \
  --mount "type=bind,src=$directory/config,dst=/config" --entrypoint node \
  'ghcr.io/accoladesolutions/helm-node@sha256:d2b82b11f2ce7f4d5b529bd7f799fc5bb8244e2b8bc16229f162b3200fd93476' src/bootstrap-admin.mjs || fail 'Administrator was not created. Service has not been started by this helper. Correct the input or permissions and rerun sh setup-admin.sh.'
unset password confirmation
printf '%s\n' 'Administrator ready. Sign in with the login name and password you chose.'

HELM_SETUP_ADMIN
  cat > "$directory/update-host.py" <<'HELM_UPDATE_HELPER'
#!/usr/bin/env python3
"""Run from the installing user's cron, outside the Node container.

Only the fixed Helm release channel can select an image. Node can request an
update through /config but never receives a Docker socket or host shell access.
"""
import fcntl
import json
import os
import re
import shutil
import subprocess
import sys
import urllib.request
from datetime import datetime, timezone
from pathlib import Path

IMAGE = re.compile(r'^ghcr\.io/accoladesolutions/helm-node@sha256:[a-f0-9]{64}$')
REVISION = re.compile(r'^[a-f0-9]{40}$')
CHANNEL = {'prod': 'https://helm-control.com', 'uat': 'https://uat.helm-control.com'}
REQUIRED = {'version', 'id', 'environment', 'image', 'revision', 'currentRevision', 'requestedAt'}
ENV = {'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
       'HOME': str(Path.home())}


def run(*args, timeout=240):
    result = subprocess.run(args, env=ENV, capture_output=True, text=True, timeout=timeout)
    if result.returncode:
        raise RuntimeError(f'{args[0]} failed ({result.returncode}): {result.stderr[-400:]}')
    return result.stdout


def private_json(path):
    if not path.exists() and not path.is_symlink():
        return None
    info = path.lstat()
    if (not path.is_file() or path.is_symlink() or info.st_mode & 0o007 or
        info.st_gid != os.getegid() or info.st_size > 8192):
        raise ValueError('Invalid private update file')
    return json.loads(path.read_text())


def atomic_json(path, value):
    temporary = path.with_name(path.name + '.tmp.' + str(os.getpid()))
    fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o640)
    try:
        os.fchmod(fd, 0o640)
        with os.fdopen(fd, 'w') as output:
            json.dump(value, output, separators=(',', ':'))
            output.write('\n')
            output.flush()
            os.fsync(output.fileno())
        os.replace(temporary, path)
    finally:
        temporary.unlink(missing_ok=True)


def release(environment):
    url = CHANNEL[environment] + '/install/helm-node/release.json'
    class NoRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, req, fp, code, msg, headers, newurl):
            raise ValueError('Release endpoint redirected')
    with urllib.request.build_opener(NoRedirect()).open(urllib.request.Request(url, headers={
        'Accept': 'application/json', 'User-Agent': 'Helm-Node-Update/0.3.2'}), timeout=20) as response:
        raw = response.read(8193)
        if len(raw) > 8192:
            raise ValueError('Release document too large')
        document = json.loads(raw)
    if (not isinstance(document, dict) or document.get('environment') != environment or
        document.get('anonymousLayersVerified') is not True or
        document.get('anonymousManifestsVerified') is not True or
        not IMAGE.fullmatch(document.get('image', '')) or
        not REVISION.fullmatch(document.get('revision', ''))):
        raise ValueError('Invalid verified release for this environment')
    return document


def compose_command(directory):
    return ('docker', 'compose', '--project-directory', str(directory), '--env-file', str(directory / '.env'),
            '-f', str(directory / 'compose.yaml'))


def inspect_image(image):
    return json.loads(run('docker', 'image', 'inspect', image, '--format', '{{json .}}'))


def inspect_container():
    return json.loads(run('docker', 'inspect', 'helm-node', '--format', '{{json .}}'))


def update(directory, environment, request, status):
    if (not isinstance(request, dict) or set(request) != REQUIRED or request['version'] != 1 or
        request['environment'] != environment or not re.fullmatch(r'[a-f0-9-]{36}', request['id']) or
        not IMAGE.fullmatch(request['image']) or not REVISION.fullmatch(request['revision']) or
        not REVISION.fullmatch(request['currentRevision'])):
        raise ValueError('Invalid update request')
    age = (datetime.now(timezone.utc) - datetime.fromisoformat(request['requestedAt'].replace('Z', '+00:00'))).total_seconds()
    if age < -30 or age > 900:
        raise ValueError('Update request expired')
    published = release(environment)
    if (request['image'], request['revision']) != (published['image'], published['revision']):
        raise ValueError('Published release changed; request a fresh update')
    current = inspect_container()
    old = current['Config']['Image']
    if not IMAGE.fullmatch(old):
        raise ValueError('Existing Node image is not immutable')
    current_revision = inspect_image(old)['Config']['Labels'].get('org.opencontainers.image.revision')
    if current_revision == request['revision'] and old == request['image']:
        return 'Node already runs the requested release.'
    if current_revision != request['currentRevision']:
        raise ValueError('Installed Node revision changed after this request')
    source = (directory / 'compose.yaml').read_text()
    if source.count(old) != 2:
        raise ValueError('Unexpected Node image references in Compose')
    compose = compose_command(directory)
    before = json.loads(run(*compose, 'config', '--format', 'json'))
    if before['services']['helm-node']['image'] != old or before['services']['helm-node']['environment']['LOCAL_SERVICE_IMAGE'] != old:
        raise ValueError('Node deployment configuration differs from the installed image')
    status('updating', request['revision'], 'Downloading and verifying the published Node image.')
    run('docker', 'pull', request['image'], timeout=600)
    candidate = inspect_image(request['image'])
    labels = candidate['Config']['Labels']
    if (labels.get('org.opencontainers.image.revision') != request['revision'] or
        labels.get('org.opencontainers.image.source') != 'https://github.com/AccoladeSolutions/helm-control-node' or
        candidate['Architecture'] != before['services']['helm-node']['platform'].split('/')[-1]):
        raise ValueError('Downloaded image identity or platform does not match the release')
    backup_root = directory / 'self-update-backups'
    backup_root.mkdir(mode=0o700, exist_ok=True)
    if backup_root.is_symlink() or not backup_root.is_dir():
        raise ValueError('Invalid private update backup directory')
    os.chmod(backup_root, 0o700)
    backup = backup_root / request['id']
    backup.mkdir(mode=0o700, exist_ok=False)
    shutil.copy2(directory / 'compose.yaml', backup / 'compose.yaml')
    revision_file = directory / 'release-revision.txt'
    if revision_file.exists():
        shutil.copy2(revision_file, backup / 'release-revision.txt')
    replacement = source.replace(old, request['image'])
    temporary = directory / ('compose.yaml.tmp.' + request['id'])
    temporary.write_text(replacement)
    # The installation owner may differ from the account running the update
    # helper. Keep the original deployment group able to administer Compose.
    os.chmod(temporary, 0o660)
    os.replace(temporary, directory / 'compose.yaml')
    try:
        after = json.loads(run(*compose, 'config', '--format', 'json'))
        expected = json.loads(json.dumps(before))
        expected['services']['helm-node']['image'] = request['image']
        expected['services']['helm-node']['environment']['LOCAL_SERVICE_IMAGE'] = request['image']
        if after != expected:
            raise ValueError('Compose changed beyond the Node image reference')
        run(*compose, 'up', '-d', '--no-deps', '--pull', 'never', '--wait', '--wait-timeout', '180', 'helm-node')
        installed = inspect_container()
        if installed['Config']['Image'] != request['image'] or installed['State']['Health']['Status'] != 'healthy':
            raise ValueError('Updated Node did not become healthy')
        if sorted(installed['Mounts'], key=lambda item: item['Destination']) != sorted(current['Mounts'], key=lambda item: item['Destination']):
            raise ValueError('Persistent mounts changed during update')
        port_line = next(line for line in (directory / '.env').read_text().splitlines() if line.startswith('PORT='))
        port = int(port_line.split('=', 1)[1]); assert 1024 <= port <= 65535
        with urllib.request.urlopen(f'http://127.0.0.1:{port}/healthz', timeout=10) as response:
            health = json.load(response)
        if health.get('status') != 'ok' or health.get('revision') != request['revision']:
            raise ValueError('Node reported the wrong health or source revision')
        revision_file.write_text(request['revision'] + '\n')
    except Exception:
        shutil.copy2(backup / 'compose.yaml', directory / 'compose.yaml')
        if (backup / 'release-revision.txt').exists():
            shutil.copy2(backup / 'release-revision.txt', revision_file)
        run(*compose, 'up', '-d', '--no-deps', '--pull', 'never', '--wait', '--wait-timeout', '180', 'helm-node')
        raise
    return 'Node updated and healthy. Models and local settings were preserved.'


def main(directory):
    directory = directory.resolve(strict=True)
    config = directory / 'config'
    if not config.is_dir() or config.is_symlink():
        raise ValueError('Expected a private Node configuration directory')
    environment = next((line.split('=', 1)[1] for line in (directory / '.env').read_text().splitlines()
                        if line.startswith('LOCAL_SERVICE_FLEET_SETUP=')), None)
    if environment not in CHANNEL:
        raise ValueError('Node release channel is missing')
    lock = directory / 'update.lock'
    with open(lock, 'a+') as handle:
        try: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError: return
        status_file = config / 'update-status.json'
        previous = private_json(status_file) or {}
        def status(phase, revision=None, message=None):
            atomic_json(status_file, {'version': 1, 'environment': environment,
                                      'checkedAt': datetime.now(timezone.utc).isoformat(),
                                      'phase': phase, 'revision': revision, 'message': message})
        request_file = config / 'update-request.json'
        request = private_json(request_file)
        if request is None:
            status(previous.get('phase', 'ready'), previous.get('revision'), previous.get('message'))
            return
        try:
            if not isinstance(request, dict):
                raise ValueError('Invalid update request')
            status('queued', request.get('revision'), 'Waiting for the host update helper.')
            message = update(directory, environment, request, status)
            status('complete', request['revision'], message)
        except Exception as error:
            status('failed', request.get('revision') if isinstance(request, dict) else None, str(error)[:400])
        finally:
            request_file.unlink()


if __name__ == '__main__':
    if len(sys.argv) != 3 or sys.argv[1] != '--directory':
        raise SystemExit('Usage: update-host.py --directory PATH')
    main(Path(sys.argv[2]))

HELM_UPDATE_HELPER
  chmod 700 "$directory/update-host.py"
  {
    printf '%s\n' '#!/bin/sh' 'set -eu'
    printf "directory='%s'\nproject_name='%s'\n" "$directory" "$project_name"
    cat <<'HELM_UPDATE_ENABLE'
command -v python3 >/dev/null 2>&1 || { echo 'Self-update requires Python 3.' >&2; exit 1; }
command -v crontab >/dev/null 2>&1 || { echo 'Self-update requires cron.' >&2; exit 1; }
command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet cron || { echo 'Start the cron service before enabling self-update.' >&2; exit 1; }
current=$(crontab -l 2>/dev/null || true)
if ! printf '%s\n' "$current" | grep -Fq "# helm-node:$project_name"; then
  { printf '%s\n' "$current"
    printf "* * * * * '%s' '%s/update-host.py' --directory '%s' >/dev/null 2>&1 # helm-node:%s\n" "$(command -v python3)" "$directory" "$directory" "$project_name"
  } | crontab -
fi
python3 "$directory/update-host.py" --directory "$directory"
printf 'Self-update helper enabled for %s.\n' "$directory"
HELM_UPDATE_ENABLE
  } > "$directory/enable-update.sh"
  chmod 700 "$directory/enable-update.sh"
  # Supplementary numeric groups grant access to configuration and host DRM devices.
  for group in $device_groups; do
    printf '      - "%s"\n' "$group"
  done > "$directory/device-groups.txt"
  # write_compose includes device groups directly; this file is only an operator record.
  printf '%s\n' '2603c0d5ac1343850296439f1b19de9ed5995c60' > "$directory/release-revision.txt"
  cd -- "$directory"
  # Ignore inherited Compose/application variables (including model paths and tokens).
  compose() { env -i PATH="$PATH" HOME="$HOME" DOCKER_HOST="$docker_endpoint" DOCKER_CONFIG="${DOCKER_CONFIG:-$HOME/.docker}" docker compose --env-file "$directory/.env" -f "$directory/compose.yaml" "$@"; }
  compose config --quiet || fail "Invalid Compose configuration. Files preserved in $directory"
  printf 'Prepared Helm Node (%s) in %s\n' "$backend" "$directory"
  if [ "$prepare_only" = true ]; then
    if [ "$setup_mode" = browser ]; then
      printf '%s\n' 'Review compose.yaml and the private .env, then follow the startup commands below from that directory.'
      printf 'After startup, open the private %s/first-start.html to choose local or Fleet setup.\n' "$directory"
    else
    printf '%s\n' 'Review compose.yaml and the private .env. After pulling images, run sh setup-admin.sh to choose your login and password before starting Node.'
    fi
    printf '%s\n' 'docker compose pull' 'docker compose run --rm --no-deps -T helm-runtime-installer'
    printf 'docker compose run --rm --no-deps -T --entrypoint node helm-node src/runtime-probe.mjs %s\n' "$backend"
    printf '%s\n' 'docker compose up -d --no-deps --wait --wait-timeout 180 helm-node'
    printf 'After startup, run sh %s/enable-update.sh to enable self-update.\n' "$directory"
    print_access_urls
    printf '%s\n' 'Prepared only: container GPU access, listeners and inference have not been tested.'
    return
  fi
  compose pull || fail "Image download failed. Files preserved in $directory; retry docker compose pull there."
  compose run --rm --no-deps -T helm-runtime-installer || fail "Runtime installation failed. Files preserved in $directory; inspect runtime installer output before retrying."
  compose run --rm --no-deps -T --entrypoint node helm-node src/runtime-probe.mjs "$backend" || fail "Container GPU probe failed for $backend. Node was not started. Check the driver, container GPU access and runtime; files are preserved in $directory."
  if [ "$setup_mode" != browser ]; then
    sh "$directory/setup-admin.sh" || fail "Administrator setup incomplete. Files preserved in $directory. Rerun sh setup-admin.sh there before docker compose up -d --wait."
  fi
  compose up -d --no-deps --wait --wait-timeout 180 helm-node || fail "Startup failed. Files preserved in $directory; inspect docker compose logs and selected address/port bindings."
  if ! sh "$directory/enable-update.sh"; then
    printf 'Node is running. Host self-update remains unavailable until you run sh %s/enable-update.sh successfully.\n' "$directory" >&2
  fi
  printf '\nHelm Node is responding at http://127.0.0.1:%s\n' "$port"
  if [ "$setup_mode" = browser ]; then
    open_first_start
  else
    printf '%s\n' 'Sign in with the local administrator login name and password you chose during installation.'
  fi
  print_access_urls
  [ "$bindings" != 127.0.0.1 ] || printf '%s\n' 'For a remote host, use an SSH tunnel. The service is not exposed to the network.'
  printf '%s\n' 'Next: verify detected GPUs, add a model, start a profile and test inference. Service health is not an inference test.'
}

# Keep execution at the end so an incomplete download cannot start installation.
main "$@"
