#!/usr/bin/env bash
#
# G8way Linux host agent — one-line installer.
#
#   curl -fsSL https://g8way.g8support.com/install-host.sh | sudo bash
#
# That one fixed line needs NO key and NO variables (card 8Je719F5, keyless
# Linux install 4/4):
#   * A new machine registers as PENDING: it shows up in the G8way console
#     (Fleet, Pending) and nothing can connect to it until an administrator
#     approves it. It then connects by itself, with no second command.
#   * An unapproved machine is deleted automatically after 30 days.
#   * Run the SAME line again to update an installed host: its identity (and
#     therefore its G8way ID), org and unattended/shell settings are kept.
#   * With no display server a FIRST install treats the machine as a server (unattended,
#     terminal offered); with a screen the person at it is asked to click Allow.
#
# Behaviour:
#   * Downloads the right release binary for this machine's architecture.
#   * Writes an agent.env config.
#   * Sets up autostart:
#       - root / passwordless-sudo -> system-wide systemd unit (g8way-host),
#                                     enabled + started.
#       - no root                  -> userspace systemd --user + linger, or,
#                                     if systemd-user isn't usable, an
#                                     @reboot crontab entry + immediate launch
#                                     (covers the sudo-blocked 4X box).
#
# The agent's 9-digit G8wayID is derived from its persisted identity key
# (stable across restarts); it cannot be forced via env.
#
# Optional overrides (an explicit variable always beats a remembered setting):
#   ... | G8WAY_FLEET_ENROLL_KEY=g8_enroll_xxx bash
#                                             # enrol straight into an org with a
#                                             # one-time key from the console
#   ... | G8WAY_HUB_URL=wss://host/ws bash    # point at a different hub
#   ... | G8WAY_UNATTENDED=1 bash             # auto-approve incoming sessions
#   ... | G8WAY_AUTO_APPROVE_NO_2FA_IDS=<id> bash
#                                             # admit a MACHINE identity (our
#                                             # AI) that can never hold a 2FA
#                                             # code. Humans are unaffected.
#   ... | G8WAY_FORCE_USER=1 bash             # force the userspace path
#
# Run through a remote shell with a short timeout (the g8way MCP shell, ssh with
# a timeout)? A restart with an open session can hang the stop for ~90 s and
# kill this script mid-swap. Close every session to the host first, and detach:
#   sudo systemd-run --collect --unit=g8way-install bash -c \
#     'curl -fsSL https://g8way.g8support.com/install-host.sh | bash'
set -euo pipefail

BASE_URL="${G8WAY_BASE_URL:-https://g8way.g8support.com/download}"
HUB_URL="${G8WAY_HUB_URL:-wss://g8way.g8support.com/ws}"
UNATTENDED="${G8WAY_UNATTENDED:-}"
AUTO_APPROVE_IDS="${G8WAY_AUTO_APPROVE_IDS:-}"
# Machine identities admitted WITHOUT a 2FA attestation. A service principal
# has no phone and no authenticator, so it can never produce a second factor
# and the ordinary allowlist can never admit it - `*` deliberately does not
# cover a no-2FA connect, because "* plus no 2FA" would mean "admit anybody
# the hub will route".
#
# Carried HERE, at install time, so the value lands in agent.env before the
# service is ever started. It used to be appended afterwards by the caller,
# which meant restarting a service seconds after its first start - and that
# first start is the one that trades the enrollment key. Both machines added
# on 2026-09-22 reported `failed` on the first run and only came up on a
# re-run (card 8EFdmuXY).
AUTO_APPROVE_NO_2FA_IDS="${G8WAY_AUTO_APPROVE_NO_2FA_IDS:-}"
# ── Full admin: the two halves the AGENT needs, neither of which anything
# used to write ────────────────────────────────────────────────────────────
#
# Measured 2026-09-22 on three freshly installed machines: the hub grants were
# set correctly and a privileged command was STILL refused, because full admin
# needs a second yes from the HOST and nothing had ever put it there. The hub
# says so itself on every boot:
#
#   step-up signer loaded - pin this in agent shell-policy.json
#   stepup_signer_pubkeys
#
# The hub mints a short-lived, signed assertion; the agent honours it only when
# that signer is PINNED here and the calling operator is NAMED here. With both
# lists empty - which is what "no shell-policy.json" means - every full-admin
# call is denied fail-closed. That is correct behaviour and it meant the
# feature could never work on a machine installed the normal way.
#
# NOT BAKED INTO THE PUBLISHED SCRIPT. The signer key is per-hub, so it is read
# from the environment at run time, exactly like the enrollment key. A key
# baked into a public download is a key shared by everyone who downloads it.
STEPUP_SIGNER="${G8WAY_STEPUP_SIGNER_PUBKEY:-}"
# Whether an elevated command must ALSO carry a fresh hub-signed step-up
# assertion. Defaults to true, which is the agent default and the safe one.
# Setting it to 0 arms full admin with NO second factor at the moment of use:
# anyone on the operator list can run anything as root, unattended. That is a
# deliberate posture, not a convenience, so it is warned about when written.
REQUIRE_STEPUP="${G8WAY_REQUIRE_STEPUP:-}"
PTY_ENABLED="${G8WAY_PTY_ENABLED:-}"
FULL_ADMIN_OPERATORS="${G8WAY_FULL_ADMIN_OPERATORS:-}"
# Card 6ab60fd8 criterion 4, found by RUNNING one rather than reading the
# file. shell-exec is OFF in the agent unless G8WAY_ALLOW_SHELL=1 is in its
# environment, and this script never wrote that variable. So a host
# installed with full admin armed - exactly the happy path criteria 1 to 3
# describe - answered EVERY command, elevated or not, with "shell_exec is
# disabled on this host", BEFORE the policy was ever consulted. The file
# said full_admin, this script said ARMED, and nothing could run. Measured
# 2026-09-28 over the wire on a live Linux host.
ALLOW_SHELL="${G8WAY_ALLOW_SHELL:-}"
# ── How this host authenticates to the hub ──────────────────────────────
#
# PREFERRED: a PER-MACHINE, single-use enrollment key minted by an operator
# at POST /fleet/enrollment-keys. On first start the agent trades it at
# POST /fleet/enroll for a registration credential derived from the hub
# master and bound to THIS machine's (pubkey, g8way_id):
#   curl -fsSL .../install-host.sh | G8WAY_FLEET_ENROLL_KEY=g8_enroll_xxx bash
#
# LEGACY: the hub's fleet-wide secrets.toml registration_token_secret.
#   curl -fsSL .../install-host.sh | G8WAY_REGISTRATION_TOKEN_SECRET=... bash
#
# SECURITY: this script is served from a PUBLIC URL. It must never be
# published with either value baked into it — a published copy carrying the
# fleet-wide secret is exactly the leak the enrollment path exists to close
# (anyone who downloaded it could register or evict arbitrary G8way IDs).
# Both are read from the ENVIRONMENT at run time and default to empty.
ENROLL_KEY="${G8WAY_FLEET_ENROLL_KEY:-}"
REG_SECRET="${G8WAY_REGISTRATION_TOKEN_SECRET:-}"
BIN_NAME="g8way-agent-linux"

say()  { printf '\033[1;32m[g8way]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[g8way]\033[0m %s\n' "$*" >&2; }
die()  { printf '\033[1;31m[g8way]\033[0m %s\n' "$*" >&2; exit 1; }
# The downloaded binary is staged in $TMP. A failed download (die) or an
# interrupt must not leave it behind; after a successful install the file is
# already moved or removed and this is a no-op.
TMP=""
cleanup_tmp() { [ -z "${TMP:-}" ] || rm -f "$TMP" 2>/dev/null || true; }
trap cleanup_tmp EXIT

case "$(uname -m)" in
  x86_64|amd64) ARCH="amd64" ;;
  aarch64|arm64) ARCH="arm64" ;;
  *) die "Unsupported architecture: $(uname -m)" ;;
esac
ASSET_URL="$BASE_URL/${BIN_NAME}-linux-${ARCH}"

fetch() { # fetch <url> <dest>
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then
    wget -qO "$2" "$1"
  else
    die "Need curl or wget to download $1"
  fi
}

# sudo / root detection. G8WAY_FORCE_USER=1 forces the userspace path.
SUDO=""
if [ "${G8WAY_FORCE_USER:-0}" = "1" ]; then
  ROOTABLE=0
elif [ "$(id -u)" -eq 0 ]; then
  SUDO=""
  ROOTABLE=1
elif command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null; then
  SUDO="sudo"
  ROOTABLE=1
else
  ROOTABLE=0
fi

# Write shell-policy.json, or say plainly why full admin will not work.
#
# Takes the data directory the agent actually reads, which is the systemd
# StateDirectory (/var/lib/g8way), NOT /etc/g8way. Getting that wrong produces
# a file nobody loads and a feature that stays silently off, which is the
# failure this whole change exists to end.
# Does this machine have a display server at all?
#
# Asked so the installer can decide whether to offer a shell. It is a
# question about the MACHINE, not about the session running the installer:
# this script is normally reached as `curl ... | sudo bash`, which inherits
# no DISPLAY even on a desktop, so keying on that variable alone would call
# every desktop headless and hand out root shells.
#
# Returns 0 (true, "has a display") on ANY sign of one. Failing towards "has
# a display" is the safe direction: the cost of being wrong that way is an
# operator seeing the capture-unavailable screen, and the cost of being wrong
# the other way is a shell on a machine nobody asked to expose one.
has_display_server() {
  # An X or Wayland socket is a server that is running right now.
  for _s in /tmp/.X11-unix/X*; do [ -e "$_s" ] && return 0; done
  for _s in /run/user/*/wayland-*; do [ -e "$_s" ] && return 0; done
  # A seat with a graphical session, per logind.
  if command -v loginctl >/dev/null 2>&1; then
    if loginctl list-sessions --no-legend 2>/dev/null | grep -qE ' (x11|wayland)$'; then
      return 0
    fi
  fi
  # Configured to boot into a desktop, even if nobody is logged in yet.
  if command -v systemctl >/dev/null 2>&1; then
    case "$(systemctl get-default 2>/dev/null)" in
      graphical.target) return 0 ;;
    esac
  fi
  # And the obvious one last, for a run from an actual desktop terminal.
  [ -n "${DISPLAY:-}" ] && return 0
  [ -n "${WAYLAND_DISPLAY:-}" ] && return 0
  return 1
}

# Decide G8WAY_PTY_ENABLED and say which way it went.
#
# The agent has shipped a working PTY since 2026-09-02 and it reads
# G8WAY_PTY_ENABLED to decide whether to offer it. Nothing on any install path
# had ever written that line, so every Linux host we have ever installed
# answers "no shell here", the viewer takes its capture-unavailable branch,
# and an operator connecting to a server with no screen gets an apology
# instead of the one thing that machine can usefully give them.
#
# A PTY is an interactive shell as the user the agent runs as, which under
# systemd is root, so this is NOT armed everywhere. It is armed where a shell
# is the only surface the product has, and left off where there is a screen to
# share - which is the same rule the viewer applies one layer up. An explicit
# G8WAY_PTY_ENABLED beats the detection in both directions.
resolve_pty_posture() {
  if [ -n "$PTY_ENABLED" ]; then
    case "$PTY_ENABLED" in
      1|true|TRUE|True) say "Interactive shell: ON (G8WAY_PTY_ENABLED was set explicitly)." ;;
      *) say "Interactive shell: OFF (G8WAY_PTY_ENABLED=$PTY_ENABLED was set explicitly)." ;;
    esac
    return 0
  fi
  if has_display_server; then
    PTY_ENABLED="0"
    say "Interactive shell: OFF. This machine has a display, so G8way shares"
    say "  the screen. Re-run with G8WAY_PTY_ENABLED=1 to offer a shell too."
  else
    PTY_ENABLED="1"
    say "Interactive shell: ON. No display server found, so a terminal is the"
    say "  only surface this machine can offer. G8WAY_PTY_ENABLED=0 refuses it."
  fi
}

# ── Keyless install (card 8Je719F5, 4/4 of 6ac6b779) ───────────────────────
#
# One fixed line, no key. A machine with no credential registers as PENDING
# (the agent makes the signed POST /fleet/pending-enroll itself, because the
# signature needs the identity key only the agent holds) and an administrator
# approves it in the console. The same line, run again, updates the host and
# KEEPS what the person chose last time.

# Where an existing install keeps its identity and settings. Plain assignments,
# not environment overrides, so a stray variable cannot point the scope rule at
# somebody else's directory. tools/tests/install-host-keyless.tests.sh sets
# them after extracting the functions below.
SYSTEM_DATA_DIR="/var/lib/g8way"
SYSTEM_ENV_FILE="/etc/g8way/agent.env"

# Which kind of install is already on this machine: system, user, other-user
# (root run via sudo while the invoking user has a userspace install), or
# nothing. A machine must never flip scope: that would mint a second identity
# and a second G8wayID for the same box.
EXISTING_SCOPE=""
detect_existing_install() {
  EXISTING_SCOPE=""
  if $SUDO test -e "$SYSTEM_DATA_DIR/identity.key" 2>/dev/null; then
    EXISTING_SCOPE="system"
  elif [ -e "$HOME/.local/share/g8way/identity.key" ]; then
    EXISTING_SCOPE="user"
  elif [ "$(id -u)" -eq 0 ] && [ -n "${SUDO_USER:-}" ] && command -v getent >/dev/null 2>&1; then
    _uh="$(getent passwd "$SUDO_USER" | cut -d: -f6)"
    if [ -n "$_uh" ] && [ -e "$_uh/.local/share/g8way/identity.key" ]; then
      EXISTING_SCOPE="other-user"
    fi
  fi
}

# Apply the scope rule, or refuse BEFORE anything is changed.
apply_scope_rule() {
  case "$EXISTING_SCOPE" in
    system)
      if [ "$ROOTABLE" -ne 1 ]; then
        die "This machine is already installed system-wide. Run the same line with sudo. Nothing was changed."
      fi
      ;;
    user)
      # Stay in userspace: a system install now would be a second identity.
      ROOTABLE=0
      SUDO=""
      ;;
    other-user)
      die "G8way is already installed for user $SUDO_USER on this machine. Run the same line as that user, without sudo. Nothing was changed."
      ;;
  esac
}

# The env file of the install we are about to update. Only the PATH: whether
# it can be read is `read_previous_env`'s question, asked with privilege.
previous_env_file() {
  if [ "$ROOTABLE" -eq 1 ]; then
    echo "$SYSTEM_ENV_FILE"
  else
    echo "$HOME/.config/g8way/agent.env"
  fi
}

# Print the old env file, READ WITH THE SAME PRIVILEGE THIS SCRIPT WRITES IT
# WITH ($SUDO: empty for root and for a userspace install, "sudo" otherwise).
#
# Review of d379af33 (card 6ae36302): agent.env is root 0600 now, and this
# read was a plain `[ -r ]` and `sed` as the INVOKING user. So an upgrade run
# by a sudoer saw "no readable file", kept nothing, replaced a custom hub
# address with production, dropped the shell and no-2FA settings, and on a
# keyless host with no display turned an explicit allowlist into "*".
#
# Exit status: 0 = printed; 4 = there is no such file (said by the privileged
# side itself, never inferred from a failure); anything else = it exists, or
# may exist, and could not be read (sudo refused, cat failed).
read_previous_env() { # read_previous_env <path>   (uses $SUDO)
  # shellcheck disable=SC2016  # $1 belongs to the inner sh, not this script
  $SUDO sh -c 'if [ -e "$1" ] || [ -L "$1" ]; then cat -- "$1" || exit 3; else exit 4; fi' sh "$1"
}

# Remember what the person chose on the previous run. For each setting that is
# EMPTY in this run, take its value from the old env file; an explicit variable
# in this run always wins. G8WAY_FLEET_ENROLL_KEY is deliberately NOT here: it
# is single use, and once spent the cached credential is what counts.
#
# An existing install whose settings cannot be READ is never updated: this
# stops, before anything is changed. Carrying on would write defaults over
# what the person chose, which is how an allowlist becomes "*".
KEPT_LIST=""
load_previous_posture() {
  KEPT_LIST=""
  _pf="$(previous_env_file)"
  _prev_rc=0
  _prev="$(read_previous_env "$_pf")" || _prev_rc=$?
  case "$_prev_rc" in
    0) ;;
    4)
      say "Found an existing install with no settings file ($_pf), so there is nothing to keep."
      return 0
      ;;
    *)
      die "This machine already has G8way installed, but its settings file $_pf could not be read (status $_prev_rc). The update was STOPPED and nothing was changed: carrying on would have replaced this machine's hub address and approval settings with defaults. Run the same line as root (sudo), or make that file readable to root, and try again."
      ;;
  esac
  for _pair in \
    G8WAY_UNATTENDED:UNATTENDED \
    G8WAY_AUTO_APPROVE_IDS:AUTO_APPROVE_IDS \
    G8WAY_AUTO_APPROVE_NO_2FA_IDS:AUTO_APPROVE_NO_2FA_IDS \
    G8WAY_PTY_ENABLED:PTY_ENABLED \
    G8WAY_ALLOW_SHELL:ALLOW_SHELL \
    G8WAY_HUB_URL:HUB_URL; do
    _key="${_pair%%:*}"
    _var="${_pair##*:}"
    # Empty in THIS run? (HUB_URL is defaulted at the top, so ask the env.)
    if [ "$_var" = "HUB_URL" ]; then
      [ -z "${G8WAY_HUB_URL:-}" ] || continue
    else
      [ -z "${!_var}" ] || continue
    fi
    _val="$(printf '%s\n' "$_prev" | sed -n "s/^${_key}=//p" | tail -n 1)"
    [ -n "$_val" ] || continue
    printf -v "$_var" '%s' "$_val"
    KEPT_LIST="${KEPT_LIST:+$KEPT_LIST, }$_key"
  done
  say "Found an existing install. Kept from the previous install: ${KEPT_LIST:-none}."
}

# A keyless machine with no screen is a server: nobody is there to click Allow.
# Decided once and printed; nothing here reads stdin, which is the pipe.
#
# Why "*" is safe: the machine is quarantined until an administrator approves
# it, so "*" admits nobody until Approve, and after Approve it admits only
# hub-routed, 2FA-verified operators of the org (the same posture the console's
# /j/<key>?headless=1 line writes).
#
# ONLY ON A FIRST INSTALL. An update never invents unattended access or a "*"
# allowlist: what the previous install had is what it keeps (see
# load_previous_posture), and a posture it never had is not handed out because
# the same line was run again. The agent itself admits a 2FA-verified operator
# on a machine it can prove has no screen, so nothing is lost by staying put.
resolve_unattended_posture() {
  [ -z "$UNATTENDED" ] || return 0
  if [ -n "${EXISTING_SCOPE:-}" ]; then
    say "This is an update, so the approval setting stays as it was: the person at this machine is asked for each connection (on a machine with no screen, a 2FA-verified operator is admitted)."
    say "  Re-run with G8WAY_UNATTENDED=1 to allow unattended access."
    return 0
  fi
  if has_display_server; then
    say "This machine has a screen, so the person at it is asked to click Allow for each connection."
    say "  Re-run with G8WAY_UNATTENDED=1 to allow unattended access."
  else
    UNATTENDED="1"
    if [ -z "$AUTO_APPROVE_IDS" ]; then AUTO_APPROVE_IDS="*"; fi
    say "No display server found, so this machine is treated as a server: nobody needs to click Allow (unattended), and a terminal is offered."
    say "  Re-run with G8WAY_UNATTENDED=0 to change that."
  fi
}

# The first graphical logind session type: x11, wayland or none.
session_type() {
  command -v loginctl >/dev/null 2>&1 || { echo none; return 0; }
  for _sid in $(loginctl list-sessions --no-legend 2>/dev/null | awk '{print $1}'); do
    _t="$(loginctl show-session "$_sid" -p Type --value 2>/dev/null || true)"
    case "$_t" in
      x11|wayland) echo "$_t"; return 0 ;;
    esac
  done
  echo none
}

say_session_type() {
  if [ "$(session_type)" = "wayland" ]; then
    say "This desktop runs Wayland. Until native Wayland capture ships, a viewer sees only applications running through XWayland. For the full desktop, choose \"Ubuntu on Xorg\" on the login screen."
  fi
}

# Does this agent binary know the keyless flags? Asked of the FILE, never by
# running it: an older agent ignores an unknown flag and would start for real.
binary_supports_keyless() { # binary_supports_keyless <file>
  grep -aqF -- '--print-fingerprint' "$1" 2>/dev/null
}

# A keyless install needs an agent that makes the pending call itself. The
# older published agents do not, would be refused at registration and stop in
# `failed`, so refuse BEFORE installing the file.
require_keyless_binary() { # require_keyless_binary <downloaded file>
  [ "$KEYLESS" = "1" ] || return 0
  binary_supports_keyless "$1" && return 0
  rm -f "$1"
  die "The published agent is too old to register without a key. Use a join link from the console (Fleet, Add a machine). Nothing was installed."
}

# Turn the agent's log text (stdin) into the one word the banner prints.
# The LAST matching line wins, so a host that connected and was then held shows
# its current state.
classify_agent_log() {
  _last="$(grep -aF -e 'registered with hub' -e 'waiting for an administrator to approve' -e 'hub rejected registration' | tail -n 1)"
  case "$_last" in
    *"registered with hub"*) echo CONNECTED ;;
    *"waiting for an administrator"*) echo WAITING ;;
    *"hub rejected registration"*) echo REJECTED ;;
    *) echo UNKNOWN ;;
  esac
}

# Poll the agent's journal (up to ~40 s) for the hub's answer.
# args: the journalctl scope flags ("" or "--user")
wait_for_hub_answer() {
  _w=0
  HUB_ANSWER="UNKNOWN"
  while [ "$_w" -lt 40 ]; do
    HUB_ANSWER="$($SUDO journalctl "$@" -u g8way-host --since "$START_TS" -o cat --no-pager 2>/dev/null | classify_agent_log)"
    case "$HUB_ANSWER" in
      CONNECTED|WAITING|REJECTED) return 0 ;;
    esac
    _w=$((_w + 1))
    sleep 1
  done
}

# The ID and fingerprint the person reads out to an administrator.
identity_facts() { # identity_facts <binary> <identity_path>
  G8_ID=""; G8_FP=""
  # An agent that predates --print-id does not ignore it: it STARTS (takes the
  # lock, creates the identity, and on a keyed install POSTs the single-use
  # enrollment key). Ask the FILE whether it knows the flag, never the process.
  # Such an install simply does not show its ID in the banner.
  binary_supports_keyless "$1" || return 0
  G8_ID="$($SUDO env "G8WAY_IDENTITY_PATH=$2" "$1" --print-id 2>/dev/null | head -n 1 || true)"
  G8_FP="$($SUDO env "G8WAY_IDENTITY_PATH=$2" "$1" --print-fingerprint 2>/dev/null | head -n 1 || true)"
  case "$G8_ID" in
    [0-9][0-9][0-9]\ [0-9][0-9][0-9]\ [0-9][0-9][0-9]) ;;
    *) G8_ID=""; G8_FP="" ;;
  esac
}

write_shell_policy() { # write_shell_policy <data_dir>
  _dir="$1"
  if [ -z "$STEPUP_SIGNER" ] && [ -z "$FULL_ADMIN_OPERATORS" ]; then
    # Nothing to pin. Say so rather than leaving somebody to discover it at
    # the first refused command, six weeks later.
    say "Full admin NOT enabled on this host (no G8WAY_STEPUP_SIGNER_PUBKEY)."
    say "  Read-only diagnostics still work. To enable it later, re-run with"
    say "  G8WAY_STEPUP_SIGNER_PUBKEY and G8WAY_FULL_ADMIN_OPERATORS set."
    return 0
  fi
  _armed=1
  if [ -z "$STEPUP_SIGNER" ] || [ -z "$FULL_ADMIN_OPERATORS" ]; then
    _armed=0
    # HALF of it is worse than none: it looks configured and denies everything.
    warn "Full admin is only half configured, so it will still refuse."
    if [ -n "$STEPUP_SIGNER" ]; then
      warn "  G8WAY_STEPUP_SIGNER_PUBKEY: set"
    else
      warn "  G8WAY_STEPUP_SIGNER_PUBKEY: MISSING"
    fi
    if [ -n "$FULL_ADMIN_OPERATORS" ]; then
      warn "  G8WAY_FULL_ADMIN_OPERATORS: set"
    else
      warn "  G8WAY_FULL_ADMIN_OPERATORS: MISSING"
    fi
    warn "  Both are required. Writing what was given anyway."
  fi

  _ops=""
  _old_ifs="$IFS"
  IFS=','
  for _o in $FULL_ADMIN_OPERATORS; do
    _o="$(echo "$_o" | tr -d '[:space:]')"
    [ -z "$_o" ] && continue
    if [ -n "$_ops" ]; then _ops="$_ops, "; fi
    _ops="$_ops\"$_o\""
  done
  IFS="$_old_ifs"

  _signers=""
  if [ -n "$STEPUP_SIGNER" ]; then _signers="\"$STEPUP_SIGNER\""; fi

  # THE FIELD THIS FILE EXISTED WITHOUT FOR ITS WHOLE LIFE.
  #
  # Until 2026-09-25 this wrote the two lists and nothing else, then printed
  # "full admin armed". ShellPolicyMode deserialises to its #[default], which
  # is Allowlist, and the gate reads
  #   if self.mode != ShellPolicyMode::FullAdmin || !operator_is_trusted(..)
  # so EVERY host ever told full admin was armed has been read-only. The lists
  # were pinned, correct, and never consulted. Ammon hit this on four machines:
  # he had pinned the operator key himself and still could not run a command.
  #
  # The mode now states what was actually armed, and the message below is not
  # permitted to claim more than the file does.
  if [ "$_armed" = "1" ]; then _mode="full_admin"; else _mode="allowlist"; fi

  # THE SAME RULE AS EVERYTHING ELSE IN THIS SCRIPT. Card 6abb7697.
  #
  # This was `0|false|FALSE|False|no|NO`, a hand-written list, while
  # G8WAY_UNATTENDED twenty lines down computed its answer. So `no` meant
  # TRUE there and FALSE here, in one script, and here it is the value that
  # DISABLES the second factor on root access.
  #
  # ONE BEHAVIOUR CHANGE, AND IT IS DELIBERATE: `no` and `NO` used to turn
  # step-up OFF and now leave it ON, because they are neither "0" nor any
  # casing of "false". That is the safe direction, it makes all three
  # variables agree, and the exposure is small: this field has only been
  # written since 2026-09-29, when the installer first learned to emit it at
  # all. `0` and every casing of `false` still turn it off, which is how the
  # message below tells people to do it.
  if _is_false_value "$REQUIRE_STEPUP"; then _stepup="false"; else _stepup="true"; fi

  $SUDO mkdir -p "$_dir"
  printf '%s\n' \
    '{' \
    '  "version": 1,' \
    "  \"mode\": \"$_mode\"," \
    "  \"require_stepup\": $_stepup," \
    "  \"stepup_signer_pubkeys\": [$_signers]," \
    "  \"full_admin_operators\": [$_ops]" \
    '}' | $SUDO tee "$_dir/shell-policy.json" >/dev/null
  $SUDO chmod 0644 "$_dir/shell-policy.json"
  if [ "$_armed" != "1" ]; then
    warn "Wrote $_dir/shell-policy.json with mode=allowlist: full admin is NOT armed."
  elif [ "$_stepup" = "false" ]; then
    warn "Wrote $_dir/shell-policy.json (full admin ARMED, require_stepup=false)."
    warn "  Every listed operator can run ANY command as root on this machine,"
    warn "  unattended, with no second factor at the moment of use. The agent"
    warn "  logs a warning on each such command. Re-run with"
    warn "  G8WAY_REQUIRE_STEPUP=1 to put the second factor back."
    _shell_exec_posture
  else
    say "Wrote $_dir/shell-policy.json (full admin armed, step-up required)."
    _shell_exec_posture
  fi
}

# THREE STATES, NOT TWO, and getting that wrong is what the 2026-09-29 review of
# this card caught. The agent decides in `shell_exec_enabled()`
# (crates/g8way-agent-linux/src/bin/agent.rs):
#
#     Some("1") => true
#     Some("0") => false
#     _         => G8WAY_UNATTENDED is set and is not 0/false
#
# The first version of this message tested `[ -n "$ALLOW_SHELL" ]`, which is TWO
# states, and was wrong in BOTH directions: it announced ENABLED for the literal
# "0" (the one value that means explicitly off), and it announced OFF when the
# variable was unset even though an UNATTENDED host reaches the fallback and has
# shell-exec ON. The second of those is the dangerous one - it tells an operator
# root shell is unreachable on a machine where it is reachable.
#
# `tools/tests/install-host-shell-policy.tests.sh` pins the agent's three arms
# as well as this function, so if anybody changes `shell_exec_enabled` this goes
# red instead of drifting quietly.
# IS THIS ENV VAR FALSE? ONE IMPLEMENTATION, BECAUSE THIS IS THE FOURTH TIME.
#
# The agent computes it in `env_value_means_on` (agent-core/host_toggles.rs) as
#
#     let v = raw.trim();
#     !(v == "0" || v.eq_ignore_ascii_case("false"))
#
# THE `.trim()` IS PART OF THE RULE, and card 6abb7697 left it out of both this
# comment and the code below. Card 6abbaae7. Without it ` false`, `false `,
# ` 0` and `0 ` are false to the AGENT and not-false here, so this script would
# announce the opposite posture to the one the machine actually takes. A padded
# value is not exotic: it is what a copy-paste into an env file, or a trailing
# space on a runbook line, produces.
#
# Card 6abb7697. This script had that computation for G8WAY_UNATTENDED and a
# HAND-WRITTEN LIST for G8WAY_REQUIRE_STEPUP two hundred lines away, so in one
# script `no` meant TRUE for one variable and FALSE for the other - and the one
# it meant FALSE for is the one that turns off the second factor guarding root.
# Card 6ab60fd8 was bounced TWICE for hand-enumerating this same set. A list
# cannot track a computation, so there is now exactly one of these.
#
# NOT EVERY SWITCH USES THIS RULE, and that is deliberate rather than an
# oversight to tidy up. `G8WAY_PTY_ENABLED` is read by the agent's
# `pty_session::enabled_by_deployment` as `v == "1" || eq_ignore_ascii_case("true")`
# - FAIL-CLOSED, because a PTY is an interactive shell as the user the agent
# runs as, which under systemd is root, so a typo must not turn it ON. This
# rule is the opposite way round: a typo means ON, which is right for a switch
# whose worst case is a black desktop for one session. Routing PTY through this
# helper would silently default a root shell to enabled. Note also that
# `enabled_by_deployment` does NOT trim, so a padded value must not be trimmed
# for that variable either. See `resolve_pty_posture` above.
#
# Returns 0 (shell-true) when the value is false.
_is_false_value() { # _is_false_value <value>
  # Trim first, exactly as `raw.trim()` does, then compare.
  _ifv_trimmed="$(printf '%s' "$1" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"
  [ "$_ifv_trimmed" = "0" ] && return 0
  [ "$(printf '%s' "$_ifv_trimmed" | tr '[:upper:]' '[:lower:]')" = "false" ]
}

_shell_exec_posture() {
  case "${ALLOW_SHELL:-}" in
    1)
      say "  Remote shell-exec: ENABLED (G8WAY_ALLOW_SHELL=1)."
      return ;;
    0)
      warn "  REMOTE SHELL-EXEC IS OFF: G8WAY_ALLOW_SHELL=0 turns it off"
      warn "  explicitly, so nothing can run on this host and every command is"
      warn "  refused BEFORE the policy above is consulted. Re-run with"
      warn "  G8WAY_ALLOW_SHELL=1 if you meant to allow it."
      return ;;
  esac
  # G8WAY_ALLOW_SHELL is unset, so the agent falls back to G8WAY_UNATTENDED.
  #
  # MIRROR THE COMPUTATION, DO NOT ENUMERATE IT. The agent's rule is
  #
  #     !(v == "0" || v.eq_ignore_ascii_case("false"))
  #
  # i.e. anything non-empty that is neither "0" nor any casing of "false" is
  # TRUE. The first version of this block listed the falsey values by hand
  # (""|0|false|FALSE|False|no|NO) and disagreed with the agent on three of
  # them: "fAlSe" (agent OFF, this said ON) and "no"/"NO" (agent ON, this said
  # OFF). The second of those is the dangerous direction - somebody sets
  # G8WAY_UNATTENDED=no meaning "not unattended", gets remote shell ENABLED,
  # and is told nothing can run. A hand-written set cannot track a computed
  # one, so this computes.
  if [ -z "${UNATTENDED:-}" ]; then
    _shell_exec_off
    return
  fi
  if _is_false_value "$UNATTENDED"; then
    _shell_exec_off
  else
    say "  Remote shell-exec: ENABLED, because this is an unattended host and"
    say "  G8WAY_ALLOW_SHELL is unset, so the agent follows G8WAY_UNATTENDED."
    say "  Set G8WAY_ALLOW_SHELL=0 if you want full admin armed but no remote"
    say "  commands."
  fi
}

# The "off because nothing turned it on" wording, in one place so the two
# callers above cannot drift from each other the way this function drifted
# from the agent.
_shell_exec_off() {
  warn "  REMOTE SHELL-EXEC IS OFF on this host, so nothing can run yet:"
  warn "  every command is refused BEFORE the policy above is consulted."
  warn "  Re-run with G8WAY_ALLOW_SHELL=1 to turn it on."
}

# An identity.key written by an agent older than the tight-perms rework kept
# whatever the umask allowed, which is normally 0644 - any local account can
# then read the host's raw private identity key and impersonate this machine
# to the hub (found on ac-inf-02, 2026-09-22). The agent corrects this itself
# on start now, but do it here as well: an upgrade should not leave the key
# exposed for the seconds between unpacking the binary and the service
# actually coming up, and an install that never restarts cleanly still gets
# fixed.
tighten_identity_key() { # tighten_identity_key <identity_path>
  _key="$1"
  [ -f "$_key" ] || return 0
  _mode="$(stat -c '%a' "$_key" 2>/dev/null || stat -f '%Lp' "$_key" 2>/dev/null || echo '')"
  # Same rule as the agent's `mode_is_owner_only`: nothing for group or other.
  # A literal allowlist was tried first and got 0700 and 0500 wrong, rewriting
  # them AND telling the operator the key had been exposed when it had not.
  if [ -n "$_mode" ] && [ "$(( 0$_mode & 077 ))" -eq 0 ]; then
    return 0
  fi
  if [ -n "$_mode" ]; then
    warn "identity.key was mode $_mode; tightening it to 0600."
    warn "It was readable by other local accounts, so consider rotating this host's key."
  else
    warn "Could not read the mode of identity.key; setting it to 0600 to be sure."
  fi
  $SUDO chmod 0600 "$_key" 2>/dev/null || warn "Could not chmod 0600 $_key"
}

# agent.env holds the fleet enrollment key (or the registration secret), so it
# is a secret file: 0600, nothing for group or other. It used to be written
# with plain `tee`, which leaves the umask's 0644 on a new file and KEEPS
# whatever mode an existing file had, so a reinstall never repaired it
# (card 6ae36302, found world-readable on the dispatcher VM). Reset the mode
# BEFORE the secret goes in, so it is never readable even for a moment, and
# on every run, so re-running this installer is the upgrade that fixes it.
# The agent also tightens it on start, for hosts that upgrade some other way.
write_env_file() { # write_env_file <path> <identity_path>   (uses $SUDO)
  _env="$1"
  $SUDO rm -f "$_env.tmp"
  ( umask 077; $SUDO touch "$_env.tmp" )
  $SUDO chmod 0600 "$_env.tmp"
  render_env "$2" | $SUDO tee "$_env.tmp" >/dev/null
  $SUDO mv -f "$_env.tmp" "$_env"
  $SUDO chmod 0600 "$_env"
}

render_env() { # render_env <identity_path>
  echo "G8WAY_HUB_URL=$HUB_URL"
  echo "G8WAY_IDENTITY_PATH=$1"
  if [ -n "$UNATTENDED" ]; then echo "G8WAY_UNATTENDED=$UNATTENDED"; fi
  if [ -n "$AUTO_APPROVE_IDS" ]; then echo "G8WAY_AUTO_APPROVE_IDS=$AUTO_APPROVE_IDS"; fi
  if [ -n "$AUTO_APPROVE_NO_2FA_IDS" ]; then
    echo "G8WAY_AUTO_APPROVE_NO_2FA_IDS=$AUTO_APPROVE_NO_2FA_IDS"
  fi
  if [ -n "$PTY_ENABLED" ]; then echo "G8WAY_PTY_ENABLED=$PTY_ENABLED"; fi
  # Only when asked. Arming full admin must NOT silently switch remote
  # shell-exec on for a host whose operator never requested it; the message
  # in write_shell_policy says plainly when the two disagree instead.
  if [ -n "$ALLOW_SHELL" ]; then echo "G8WAY_ALLOW_SHELL=$ALLOW_SHELL"; fi
  # Per-host enrollment wins: on a machine that has had G8way before,
  # /etc/g8way/agent.env or registration-token.env may still hold the OLD
  # fleet-wide secret, which is WRONG (not merely redundant) once the hub
  # master is rotated. When an enrollment key is supplied we write ONLY the
  # key, so there is no path back to the leaked value on a reinstall.
  if [ -n "$ENROLL_KEY" ]; then
    echo "G8WAY_FLEET_ENROLL_KEY=$ENROLL_KEY"
  elif [ -n "$REG_SECRET" ]; then
    echo "G8WAY_REGISTRATION_TOKEN_SECRET=$REG_SECRET"
  fi
  echo "RUST_LOG=info"
}

# Wait for the service to settle, then say what it actually reached.
#
# WHY POLL AND NOT SLEEP. The hand-made join script this replaces did
# `sleep 4 && systemctl is-active`, which reports whatever the unit happened to
# be doing at four seconds. Measured on two fresh machines on 2026-09-22, from
# Ammon's own screenshots while he stood at them:
#
#   ac-inf-04   run 1  "service: failed"   run 2  "service: active"
#   ac-inf-03   run 1  "failed"   run 2  "failed"   run 3  "active"
#
# The end state was correct on both, which is exactly what made it dangerous:
# an installer that works on the second attempt teaches whoever runs it to
# shrug and re-run, and the next REAL failure gets shrugged at too.
#
# WHY THE INSTALLER AND NOT A WRAPPER. The polling fix already existed - in
# `join-linux.sh`, a hand-made file that lives ONLY on the download droplet and
# is in no repository at all. One `rm` from gone, and no path other than that
# one script ever got it. Meanwhile the installer itself said "Installed +
# started" and never checked anything, so the one-line join URL, the update
# wrapper and a plain run all reported success without looking.
#
# `systemctl is-active` exits non-zero for anything but "active", so every call
# is guarded: under `set -e` an inactive service would otherwise abort the run
# at the moment it is trying to explain itself.
report_service_state() { # report_service_state <systemctl-args...>
  _state=""
  _n=0
  _silent=0
  while [ "$_n" -lt 45 ]; do
    _state="$($SUDO systemctl "$@" is-active g8way-host 2>/dev/null || true)"
    case "$_state" in
      # `activating` and `deactivating` are the states worth waiting through;
      # these two are settled and waiting longer only delays the answer.
      active|failed) break ;;
      "")
        # EMPTY IS NOT A STATE. `is-active` always prints one of active,
        # inactive, activating, deactivating or failed; nothing at all means
        # the CALL failed - no systemd, no bus, systemctl absent. Found by
        # running this under a WSL with no systemd, where it waited the full
        # 45 seconds and then announced the agent had not come up. That is a
        # wrong answer delivered slowly, which is worse than admitting it
        # could not ask.
        _silent=$((_silent + 1))
        if [ "$_silent" -ge 2 ]; then
          _state="unknown"
          break
        fi
        ;;
      *) _silent=0 ;;
    esac
    _n=$((_n + 1))
    sleep 1
  done

  if [ "$_state" = "active" ]; then
    # CONFIRM IT STAYED UP, because "active" is weaker than it looks.
    #
    # The unit is Type=simple, so systemd calls it active the instant the
    # process is SPAWNED - before it has talked to the hub, and long before it
    # knows whether its enrollment worked. An agent that starts and then exits
    # 78 two seconds later would be reported as fine by a check that stopped
    # here, which is the same class of wrong answer this whole card is about,
    # just pointing the other way.
    #
    # RestartPreventExitStatus=78 means systemd will NOT retry that, so the
    # state settles at failed and stays there. Five seconds is enough to catch
    # it: the failure is a refusal from the hub on the first connection, not a
    # slow crash.
    _settle=0
    while [ "$_settle" -lt 5 ]; do
      sleep 1
      _settle=$((_settle + 1))
      _now="$($SUDO systemctl "$@" is-active g8way-host 2>/dev/null || true)"
      case "$_now" in
        failed) _state="failed"; break ;;
        "") break ;;
      esac
    done
  fi

  # Ask the hub's answer from the agent's own log, but only where the new
  # banner is meaningful: a keyless install, or a binary that can print an ID.
  HUB_ANSWER="UNKNOWN"
  if [ "$_state" = "active" ] && { [ "$KEYLESS" = "1" ] || [ -n "${G8_ID:-}" ]; } && [ -n "${START_TS:-}" ]; then
    wait_for_hub_answer "$@"
  fi

  echo
  echo "=================================================="
  echo "  THIS MACHINE:  $(hostname 2>/dev/null || echo unknown)"
  echo "  service:       ${_state:-unknown}"
  if [ -n "${G8_ID:-}" ]; then
    echo "  G8way ID:      $G8_ID"
    [ -z "${G8_FP:-}" ] || echo "  fingerprint:   $G8_FP"
  fi

  if [ "$_state" = "active" ]; then
    case "$HUB_ANSWER" in
      CONNECTED)
        echo "  STATUS:        CONNECTED"
        ;;
      WAITING)
        echo "  STATUS:        WAITING FOR APPROVAL"
        echo "=================================================="
        echo "  An administrator approves this machine in the G8way console (Fleet, Pending)."
        echo "  Tell them the ID${G8_FP:+ and fingerprint} above. You do not need to run anything else: the"
        echo "  machine connects by itself within about a minute of being approved."
        echo "  If nobody approves it, it is removed automatically after 30 days."
        echo "  To update it later, run the same line again; its ID and settings are kept."
        ;;
      REJECTED)
        if [ "$KEYLESS" = "1" ]; then
          echo "  STATUS:        NOT CONNECTED"
          echo
          echo "  The hub refused this machine. The reason, from the agent itself:"
          $SUDO journalctl "$@" -u g8way-host -n 20 --no-pager 2>/dev/null | sed 's/^/    /' || true
          echo "=================================================="
          return 1
        fi
        ;;
      *)
        if [ "$KEYLESS" = "1" ]; then
          echo "  STATUS:        STARTED, NO ANSWER FROM THE HUB YET"
          _why="$($SUDO journalctl "$@" -u g8way-host --since "$START_TS" -o cat --no-pager 2>/dev/null | grep -aF -e 'clock is' -e 'refused with 429' -e 'answered 429' | tail -n 1 || true)"
          case "$_why" in
            *"clock is"*)
              echo "  This machine's clock is wrong, so the hub refuses its signed request."
              echo "  Fix the time (sudo timedatectl set-ntp true), then: sudo systemctl restart g8way-host" ;;
            *429*)
              echo "  The hub's limit was hit: one network address may hold at most 5 machines"
              echo "  awaiting approval, and this address already does. Ask an administrator to"
              echo "  approve or remove those first, then: sudo systemctl restart g8way-host" ;;
          esac
          echo "  The agent keeps trying. Check: journalctl ${1:+$1 }-u g8way-host -f"
        fi
        ;;
    esac
    echo "=================================================="
    return 0
  fi

  if [ "$_state" = "unknown" ]; then
    # DID NOT FAIL - could not be asked. Reporting this as a failure would send
    # somebody looking for a broken agent when what is broken is the question.
    echo
    echo "  COULD NOT ASK systemd whether the agent is running. That is not the"
    echo "  same as the agent being down, and this install may be fine."
    echo "  Check by hand:  systemctl status g8way-host"
    echo "=================================================="
    return 0
  fi

  # NOT just "failed". The operator is standing at the machine and journalctl
  # is a separate thing to know about; the reason belongs in the banner they
  # are already reading.
  echo
  echo "  IT DID NOT COME UP. The reason, from the agent itself:"
  $SUDO journalctl "$@" -u g8way-host -n 20 --no-pager 2>/dev/null | sed 's/^/    /' || true
  echo
  echo "  Do NOT just re-run this. A second run that works hides why the first"
  echo "  did not, and the enrollment key is single use - a re-run without a"
  echo "  fresh key cannot enrol anything. Send the block above back instead."
  echo "=================================================="
  return 1
}

install_system() {
  say "Installing system-wide (systemd) ..."
  TMP="$(mktemp)"
  fetch "$ASSET_URL" "$TMP" || die "download failed: $ASSET_URL"
  require_keyless_binary "$TMP"
  $SUDO install -D -m 0755 "$TMP" /usr/bin/$BIN_NAME
  rm -f "$TMP"
  $SUDO mkdir -p /etc/g8way /var/lib/g8way
  # A previous install (or the .deb postinst) may have dropped the FLEET-WIDE
  # secret in this sidecar file, which the unit also sources. Enrolling
  # per-host must not leave that behind: once the hub master is rotated it is
  # wrong, and until then it is the leaked value sitting on the disk.
  if [ -n "$ENROLL_KEY" ] && [ -f /etc/g8way/registration-token.env ]; then
    warn "Removing the fleet-wide secret left at /etc/g8way/registration-token.env"
    warn "(this host now uses its own per-machine credential)."
    $SUDO rm -f /etc/g8way/registration-token.env
  fi
  if [ "$KEYLESS" = "1" ]; then resolve_unattended_posture; say_session_type; fi
  resolve_pty_posture
  write_env_file /etc/g8way/agent.env /var/lib/g8way/identity.key
  $SUDO chown root:root /etc/g8way/agent.env 2>/dev/null || true
  # Create the identity NOW so its ID can be shown before the service starts;
  # tighten AFTER, because the key is created under the caller's umask.
  identity_facts /usr/bin/$BIN_NAME /var/lib/g8way/identity.key
  tighten_identity_key /var/lib/g8way/identity.key
  write_shell_policy /var/lib/g8way
  $SUDO tee /lib/systemd/system/g8way-host.service >/dev/null <<'UNIT'
[Unit]
Description=G8way Linux host agent (remote support)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
EnvironmentFile=-/etc/g8way/agent.env
ExecStart=/usr/bin/g8way-agent-linux
Restart=on-failure
RestartSec=5
# 78 == EX_CONFIG: the hub rejected our registration proof (missing or wrong
# G8WAY_REGISTRATION_TOKEN_SECRET). Restarting cannot fix a config fault, and
# looping on it hides the reason — stop in `failed` so `systemctl status`
# shows it. Matches EXIT_CONFIG in crates/g8way-agent-linux/src/bin/agent.rs.
RestartPreventExitStatus=78
StateDirectory=g8way
NoNewPrivileges=true
[Install]
WantedBy=multi-user.target
UNIT
  $SUDO systemctl daemon-reload
  $SUDO systemctl enable g8way-host.service
  START_TS="$(date '+%Y-%m-%d %H:%M:%S')"
  $SUDO systemctl restart g8way-host.service
  say "Installed + started system service g8way-host."
  say "Check: sudo systemctl status g8way-host  |  journalctl -u g8way-host -f"
  # ONE start, and then we watch it. There is deliberately no second restart:
  # the first start is the one that trades the enrollment key for a per-host
  # credential, and restarting seconds later is the race this card was opened
  # about.
  report_service_state || INSTALL_FAILED=1
}

install_user() {
  say "No root/sudo (or forced) — installing in userspace ..."
  PREFIX="$HOME/.local"
  DATA_DIR="$HOME/.local/share/g8way"
  CONF_DIR="$HOME/.config/g8way"
  mkdir -p "$PREFIX/bin" "$DATA_DIR" "$CONF_DIR"
  TMP="$(mktemp)"
  fetch "$ASSET_URL" "$TMP" || die "download failed: $ASSET_URL"
  require_keyless_binary "$TMP"
  mv -f "$TMP" "$PREFIX/bin/$BIN_NAME"
  chmod 0755 "$PREFIX/bin/$BIN_NAME"
  if [ "$KEYLESS" = "1" ]; then resolve_unattended_posture; say_session_type; fi
  resolve_pty_posture
  SUDO="" write_env_file "$CONF_DIR/agent.env" "$DATA_DIR/identity.key"
  identity_facts "$PREFIX/bin/$BIN_NAME" "$DATA_DIR/identity.key"
  tighten_identity_key "$DATA_DIR/identity.key"
  # THE OTHER HALF OF THE SAME BUG. Found in review: the system-wide path
  # above writes shell-policy.json and this one did not, so a userspace
  # install kept exactly the silent-off behaviour this change exists to end -
  # full admin configured on the hub, refused by the host, with a message
  # blaming the allowlist.
  #
  # DATA_DIR, not CONF_DIR. The agent resolves its policy directory as
  # G8WAY_DATA_DIR, else the parent of G8WAY_IDENTITY_PATH (see
  # `shell_data_dir` in g8way-agent-linux). Here that identity key is written
  # under $DATA_DIR, so that is the only directory the agent will look in.
  write_shell_policy "$DATA_DIR"

  if command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1; then
    say "Using systemd --user + linger."
    UDIR="$HOME/.config/systemd/user"
    mkdir -p "$UDIR"
    cat > "$UDIR/g8way-host.service" <<UNIT
[Unit]
Description=G8way Linux host agent (remote support, userspace)
After=network-online.target
[Service]
Type=simple
EnvironmentFile=-$CONF_DIR/agent.env
ExecStart=$PREFIX/bin/$BIN_NAME
Restart=on-failure
RestartSec=5
[Install]
WantedBy=default.target
UNIT
    systemctl --user daemon-reload
    systemctl --user enable g8way-host.service
    START_TS="$(date '+%Y-%m-%d %H:%M:%S')"
    systemctl --user restart g8way-host.service
    loginctl enable-linger "$(id -un)" 2>/dev/null || \
      warn "Could not enable linger; agent may stop on logout."
    say "Installed userspace systemd unit g8way-host (user)."
    say "Check: systemctl --user status g8way-host"
    report_service_state --user || INSTALL_FAILED=1
    return
  fi

  warn "systemd --user unavailable; falling back to @reboot cron."
  LAUNCH="env \$(cat $CONF_DIR/agent.env | xargs) $PREFIX/bin/$BIN_NAME >> $DATA_DIR/agent.log 2>&1"
  CRON_LINE="@reboot $LAUNCH"
  ( crontab -l 2>/dev/null | grep -v "$BIN_NAME" ; echo "$CRON_LINE" ) | crontab -
  nohup bash -c "$LAUNCH" >/dev/null 2>&1 &
  say "Installed @reboot cron entry and launched the agent now."
  say "Logs: $DATA_DIR/agent.log"
}

# The scope rule and the remembered settings, BEFORE anything below asks which
# scope this is or which hub to dial.
detect_existing_install
apply_scope_rule
if [ -n "$EXISTING_SCOPE" ]; then load_previous_posture; fi
say "G8way host installer — arch=$ARCH hub=$HUB_URL"
# Where the agent caches the per-machine credential it traded its enrollment
# key for. `host_enrollment::credential_path_for_identity` puts it beside the
# identity key, so this must track the identity path the two install paths use.
cached_credential_path() {
  if [ "$ROOTABLE" -eq 1 ]; then
    echo /var/lib/g8way/host-registration.cred
  else
    echo "$HOME/.local/share/g8way/host-registration.cred"
  fi
}

# Which credential will this host actually register with, if any?
#
# THE ORDER MIRRORS THE AGENT'S, and it has to. `host_enrollment::provision`
# tries a fresh enrollment key, then the credential cached on this disk, then
# the legacy fleet-wide secret. A check that asked a different question would
# either refuse an install that was going to work, or bless one that was not.
#
# THE CACHED ONE IS WHY THIS IS NOT JUST "IS THE KEY SET". Until 2026-09-22
# this asked only about the two ENVIRONMENT values, so re-running the installer
# on a machine that was ALREADY enrolled printed a block warning that the hub
# would reject it - false, and the scariest text on the screen during an
# ordinary update. Worse, the version of this check that FAILS (below) would
# have refused to update every enrolled machine in the fleet.
credential_source() {
  if [ -n "$ENROLL_KEY" ]; then
    echo "a per-machine enrollment key"; return 0
  fi
  if [ -n "$REG_SECRET" ]; then
    echo "the fleet-wide registration secret"; return 0
  fi
  # -s, not -f: a zero-byte credential file is not a credential, and a half
  # written one is how a machine ends up refusing to register while everything
  # on disk says it should work.
  if $SUDO test -s "$(cached_credential_path)" 2>/dev/null; then
    echo "the per-machine credential already on this host"; return 0
  fi
  return 1
}

# NO CREDENTIAL IS NOT AN ERROR ANY MORE (card 8Je719F5).
#
# This used to die here ("No hub credential. Nothing installed") because a
# public one-liner with no key would otherwise let anyone who finds the URL put
# a machine into the fleet. The hub now holds an unkeyed machine as PENDING:
# quarantined, in no org, connectable by nobody, deleted after 30 days, until an
# administrator approves it. So with no credential this installs and the agent
# registers as pending.
#
# What stays: a keyless install against an unreachable hub fails loudly BEFORE
# anything is written (card 6ab1bb8f criterion 4), so a typo in G8WAY_HUB_URL
# leaves NO unit, NO binary and NO cron entry behind.
KEYLESS=0
if CRED_SOURCE="$(credential_source)"; then
  say "Registration: $CRED_SOURCE."
else
  case "$(printf '%s' "${G8WAY_NO_PENDING_ENROLL:-}" | tr '[:upper:]' '[:lower:]')" in
    ""|0|false) ;;
    *) die "G8WAY_NO_PENDING_ENROLL is set, so this machine may not register itself, and no key was given. Pass G8WAY_FLEET_ENROLL_KEY (Fleet, Add a machine). Nothing installed." ;;
  esac
  KEYLESS=1
  say "No key was given. This machine will join as PENDING: it shows up in the G8way console, and nothing can connect to it until an administrator approves it."
  HUB_HTTP="$(printf '%s' "$HUB_URL" | sed -e 's#^wss://#https://#' -e 's#^ws://#http://#' -e 's#/ws/*$##')"
  if ! fetch "$HUB_HTTP/healthz" /dev/null; then
    die "Cannot reach the G8way hub at $HUB_HTTP. Nothing was installed."
  fi
fi
if [ "$ROOTABLE" -eq 1 ]; then
  install_system
else
  install_user
fi
# EXIT NON-ZERO WHEN THE SERVICE DID NOT COME UP.
#
# "Done." on a machine whose agent is dead is the same false reassurance the
# credential gate above exists to prevent, one step later. The banner has
# already said what happened and why; this is the half that survives being
# piped into something, or read by the join URL's wrapper.
if [ "${INSTALL_FAILED:-0}" = "1" ]; then
  warn "Finished, but the agent is NOT running. See the block above."
  exit 1
fi
say "Done."
