#!/bin/sh
# Public Steery installer for macOS and Linux.
#
# To read this help when piping: curl -fsSL https://steery.dev/install.sh | sh -s -- --help
#
# Usage:
#   curl -fsSL https://steery.dev/install.sh | sh
#   curl -fsSL https://steery.dev/install.sh | sh -s -- --harness omp,codex --install
#   curl -fsSL https://steery.dev/install.sh | sh -s -- --install-only
#   DAYTONA_API_KEY=… curl -fsSL https://steery.dev/install.sh | sh -s -- --adapter daytona --setting DAYTONA_API_KEY
#   BOAT_API_KEY=… curl -fsSL https://steery.dev/install.sh | sh -s -- --adapter boat --setting BOAT_API_KEY
#
# Options:
#   --harness <ids>    have exactly these harnesses set up, comma-separated or repeated:
#                      one set up before and not named here is given back. With none, a
#                      terminal lists every harness a driver here knows — the ones
#                      installed here ticked, the others offered with their own
#                      installers — and asks; a run with nobody there keeps what is set up
#   --install          install a harness --harness names that is not installed here with
#                      its vendor's own installer. Without it a terminal shows the
#                      installer's command and asks; nobody there means nothing installed
#   --program <source> add the drivers and adapters of this source too, as `steery
#                      programs add <source>` does: a GitHub repository whose releases
#                      publish them, a release, a manifest's URL, an archive, or a built
#                      program's path; repeatable
#   --no-default-programs
#                      add only what --program names, not Steery's own drivers and
#                      adapters (`steery programs add` with no source)
#   --to <dir>         install directory (default: $STEERY_BIN or $HOME/.local/bin)
#   --install-only     stop after installing the binary and its programs: no sign-in, no
#                      configuration. What an agent following https://steery.dev/install.md
#                      runs; it drives `steery setup` itself from there
#   --no-color         draw nothing but text, whatever the terminal can do
#   --cpu <percent>    the share of this machine's CPU the runtime and everything it
#                      starts may use together, 1–100 (default 70). It applies only with a
#                      service: with --no-service there is nothing to share out, and setup
#                      neither asks nor uses it. With none, a terminal is asked once and a
#                      machine that chose keeps its choice
#   --custody file     keep this machine's reader key in a file on this disk, where anything
#                      that can read the file can read every answer you ever send here,
#                      including the agent the answers are about. Saying `file` is
#                      consenting to that; nothing else selects it. Without it the key goes
#                      to this machine's own hardware — the Secure Enclave, or a TPM — and
#                      setup stops on a machine that has neither
#   --no-service       do not supervise the runtime: on a computer with no launchd or
#                      systemd --user (a container, say) whoever runs this starts
#                      `steery run` itself. Setup stops on such a computer without it
#   --adapter <id>     what runs this machine's work. `local`, the default, is this
#                      computer itself. An adapter added here that makes hosts —
#                      `daytona`, `opensandbox`, `boat`, or one a --program source brings — runs each
#                      conversation in a host of its own at that provider instead, and then
#                      no agent runs on this computer at all: it only joins the machine to
#                      Steery. With none, a terminal is asked "What runs the work here?" and
#                      a machine set up before keeps its choice. An adapter id is lowercase
#                      letters, digits and dashes
#   --setting NAME[=VALUE]
#                      one of the adapter's declared settings, repeatable: an API key, a
#                      URL. NAME alone takes the value from this script's environment,
#                      which keeps a secret out of argv and out of every line printed here;
#                      a VALUE may hold `=` and spaces. A terminal is asked for each one
#                      the adapter needs and was not given; nobody there means setup stops
#                      naming it
#   --source image:<ref>|snapshot:<name>
#                      what the adapter makes each host from; absent, the adapter's own
#                      default
#   --join             this computer is a host of a machine whose hosts join it
#                      (specs/JOINED-HOSTS.md): install the binary and its programs, no
#                      setup, then run `steery host join` detached where STEERY_JOIN holds
#                      the join token `steery join <machine>` printed; without it (an image
#                      being built), print the command the host's start script runs
#   --help             print usage
#
# Getting the binary and its programs, nothing more:
#   - detects OS/arch, resolves the current versioned archive through the
#     fixed pointer <server>/downloads/steery-<target>.latest of the server it sets up for,
#   - downloads that one archive + its .sha256 sidecar over fixed HTTPS paths,
#   - verifies the SHA-256 checksum BEFORE touching anything installed,
#   - unpacks `steery` (on macOS inside the signed Steery.app) into a folder of its own
#     under <dir>/.steery/, runs it (`steery --version`), and only then moves the one
#     link <dir>/steery onto it, in a single rename. Every run installs the published
#     build: running this is asking for the current one, and a machine on it already
#     gets the same bytes again rather than a guess that they match.
#   - adds the drivers and adapters: `steery programs add --yes` of Steery's own two
#     sources and every --program, each a published binary checked against its
#     manifest's SHA-256, started and checked before it is kept. A source already added
#     is brought up to its latest release. A source that cannot be added is said with its
#     cause and the others are still tried; the run then ends with exit 1 naming it:
#     `steery` is installed, its programs are not, and running this again adds them.
# It never uses sudo, and never executes downloaded content except the
# checksum-verified binaries it installs. A failed or checksum-mismatched download, or a
# binary that does not run here, never replaces what is installed: until the link moves,
# the set that was there is the one that runs. Whether a binary runs here is decided by
# running it, never by a version number written in this script: a C library too old for
# it, or none (musl), is named from what the loader said.
#
# Which sets stay in <dir>/.steery/ is one rule for this script and for the command control
# runs to install a set in a host (machine/install.rs): the set that runs now and the one
# before it stay for whatever still runs them, and every other set and every stage is
# removed once nothing has written to it for 60 minutes; on macOS a set a live process
# runs from stays as well, whatever its age. The runtime's own updater (update.rs) keeps
# the current set and the one before and clears the others after 60 minutes, without the
# live-process exception.
#
# Exit status: 0 when it did what was asked; 1 for anything else, never 2. That includes
# `steery setup` returning its own 2, "a step of the person's is pending, then run me
# again": nothing failed, so no failure box is drawn, setup's own sentence stays as it
# printed it, the command to run again is printed as `next:`, and the exit is 1.
#
# Then it runs `steery setup`, because a binary on disk configures nothing. Setup does
# these in order, and each one is read back before the machine is called set up:
#
#   1. asks what runs the work here — this computer, or the hosts of an adapter added
#      here that makes them (Daytona, OpenSandbox, Boat), then that adapter's settings, secret
#      ones unechoed — and checks them with the provider before keeping them; then
#      lists every agent harness the drivers added here know — the ones installed here
#      ticked, the others offered with their vendors' own installers — and asks which
#      to set up; a missing one you pick is installed once you read its installer's
#      command and say yes. Then how much of this machine's CPU Steery's agents and
#      their builds may use together (70% unless you choose, each choice shown as the
#      cores it comes to) — both every time, so a machine set up before can change its mind;
#   2. puts this machine's reader key under custody — the Secure Enclave, or a TPM;
#   3. signs you in (a link and a short code, no browser needed) and creates this
#      machine's key, or finds the one it already has (on a Mac, enrolling it as a signer);
#   4. writes three things into each harness you chose and no others — the MCP entry it
#      reaches Steery through, the skill that tells its agent what to do with it, and,
#      where the harness has them, hooks on its own lifecycle events — and gives back
#      any harness you left out;
#   5. puts the runtime under launchd or systemd --user;
#   6. checks all of it: reads every harness file back, starts its own MCP server and
#      asks it for its tools, and looks for the runtime — then sends one request to your
#      phone and waits for the answer, which proves the whole path end to end.
#
# Nothing is written into a harness's files until step 4, after the sign-in, and that is
# deliberate: an MCP entry is a URL every new session dials, so a setup that stopped at
# your move with entries already written would leave every session on this machine dialling
# a closed door. A setup you walk away from before then leaves those files as they were.
# A harness you agreed to have installed is installed by its vendor's own installer after
# the sign-in, just before step 4 writes: the first thing setup does to this
# computer outside Steery's own folders, and only once you read its command and said yes
# (or --install said so).
#
# A machine whose work runs in an adapter's hosts skips the harnesses here: step 4 writes
# nothing into this computer's harnesses, and the runtime starts no turn on it. Each
# conversation gets a host of its own, made from --source, and the harnesses are set up
# inside it. The settings are kept at 0600 in this computer's Steery folder and are never
# printed again. Daytona, OpenSandbox and Boat in their clouds need no computer at all: they
# are added on steery.dev's Machines page instead.
#
# Unattended, on a machine that is set up: the binary is replaced, setup keeps what is
# set up and brings it up to the new binary, and the runtime is restarted on it. Nothing
# is installed unless --install says so. A shell with no terminal on a machine not yet
# set up installs the binary, prints the remaining command, and changes nothing else.
set -eu

# Where the published archives are: the downloads of the server this sets up for
# (STEERY_URL, as `steery` reads it), as the updater derives them. HTTPS only.
SERVER="${STEERY_URL:-https://steery.dev}"
BASE="${SERVER%/}/downloads"
DEST=""
DEST_SAID=0
INSTALL_ONLY=0
JOIN=0
NO_COLOR_FLAG=0
# What is appended to `steery setup`: `--harness`, `--install`, `--cpu`, `--custody`,
# `--no-service`, `--adapter`, `--setting` and `--source`, each validated here only as
# safe to pass; setup checks what they name. Every word is added shell-quoted, so a
# setting's value with spaces stays one word, and the line is run with `eval`. Empty
# means "let it ask", which is the whole point of the terminal path.
SETUP=""
# The same flags as they are shown: a setting's value is never printed, only its name.
SHOWN=""
# The names of the settings whose value was said on this command line (" NAME…").
VALUED=""
# Whether Steery's own drivers and adapters are added: the sources `steery programs add`
# keeps, added when it names none.
DEFAULT_PROGRAMS=1
PROGRAMS=""

# A flag this script cannot use, or an environment it cannot run in, before anything is
# drawn: said on stderr, exit 1, nothing touched.
refuse() {
  printf 'install.sh: %s\nNothing was installed.\n' "$1" >&2
  exit 1
}
# `need $# "--x needs …"`: the flag in hand has its value.
need() { [ "$1" -ge 2 ] || refuse "$2"; }
# `curl | sh` reads this script from the pipe: the rest of it is read to the end before
# exiting on --help, so curl is not left writing to a closed pipe (curl: (23)). A script
# run from a file, or from a terminal, has nothing to drain.
drain() { if [ ! -t 0 ] && [ ! -f "$0" ]; then cat >/dev/null 2>&1 || true; fi; }

usage() {
  echo "Usage:"
  echo "  curl -fsSL https://steery.dev/install.sh | sh"
  echo "  curl -fsSL https://steery.dev/install.sh | sh -s -- [options]"
  echo ""
  echo "Options:"
  echo "  --harness <ids>    have exactly these harnesses set up, comma-separated; with none,"
  echo "                     a terminal lists every one a driver here knows and asks"
  echo "  --install          install a named harness that is missing with its own installer"
  echo "                     (a terminal is asked otherwise; nobody there installs nothing)"
  echo "  --program <source> add the drivers and adapters of this source too: a GitHub"
  echo "                     repository, a release, a manifest's URL, an archive or a"
  echo "                     built program's path (repeatable)"
  echo "  --no-default-programs"
  echo "                     add only what --program names, not Steery's own"
  echo "  --to <dir>         install directory (default: \$STEERY_BIN or \$HOME/.local/bin)"
  echo "  --install-only     stop after installing the binary and its programs: no sign-in,"
  echo "                     no configuration"
  echo "  --join             a host of a machine whose hosts join it: install, then run"
  echo "                     \`steery host join\` detached with STEERY_JOIN (the token"
  echo "                     \`steery join <machine>\` prints)"
  echo "  --no-color         draw nothing but text, whatever the terminal can do"
  echo "  --cpu <percent>    the share of this machine's CPU Steery's runtime and agents may"
  echo "                     use, 1-100 (default 70; a terminal is asked once). Only with a"
  echo "                     service: --no-service has no share to set, and ignores it"
  echo "  --custody file     keep this machine's reader key in a file on this disk, where"
  echo "                     anything that can read the file can read every answer you"
  echo "                     ever send here, including the agent the answers are about;"
  echo "                     saying it is consenting to that (default: the Secure Enclave"
  echo "                     or a TPM, and setup stops where there is neither)"
  echo "  --no-service       do not supervise the runtime (no launchd or systemd --user here,"
  echo "                     as in a container): you start \`steery run\` yourself"
  echo "  --adapter <id>     what runs this machine's work: local (this computer, the"
  echo "                     default), or an adapter that makes hosts, such as daytona,"
  echo "                     opensandbox or boat, which runs each session in a host of its"
  echo "                     own there and nothing on this computer. With none, a terminal"
  echo "                     is asked, and a machine set up before keeps its choice"
  echo "  --setting NAME[=VALUE]"
  echo "                     one of that adapter's settings, repeatable. NAME alone takes"
  echo "                     the value from the environment: say a secret that way, so it"
  echo "                     is never in argv. A VALUE may hold = and spaces"
  echo "  --source image:<ref>|snapshot:<name>"
  echo "                     what each host is made from (default: the adapter's own)"
  echo "  --help             print this help"
  echo ""
  echo "Examples, for an agent or a script (nothing is asked):"
  echo "  curl -fsSL https://steery.dev/install.sh | sh -s -- --adapter local --harness omp"
  echo "  curl -fsSL https://steery.dev/install.sh | sh -s -- --adapter daytona \\"
  echo "    --setting DAYTONA_API_KEY            # DAYTONA_API_KEY exported beforehand"
  echo "  curl -fsSL https://steery.dev/install.sh | sh -s -- --adapter opensandbox \\"
  echo "    --setting OPENSANDBOX_URL=https://hosts.example.com --setting OPENSANDBOX_API_KEY"
  echo "  curl -fsSL https://steery.dev/install.sh | sh -s -- --adapter boat \\"
  echo "    --setting BOAT_API_KEY               # BOAT_API_KEY exported beforehand"
  echo ""
  echo "Daytona, OpenSandbox and Boat in their clouds need no computer: add them on steery.dev's"
  echo "Machines page. Every run installs the published build. Environment: STEERY_URL"
  echo "selects the server (HTTPS), whose downloads it installs from; NO_COLOR draws plain"
  echo "text. Setup signs you in and creates this machine's key itself; no credential of"
  echo "Steery's is ever placed in argv, and a setting's value is never printed."
  echo ""
  echo "Exit status: 0 when done, 1 for anything else; never 2."
}

# One word for `steery setup`, appended to SETUP shell-quoted, so `eval` gives it back as
# exactly one argument whatever it holds, and to SHOWN as it is printed (`$2` when the
# printed word differs, as a setting's value does). A word that needs no quoting is
# appended bare, which keeps the printed command readable.
quoted() {
  case "$1" in
    *[!A-Za-z0-9_./:=@%+,-]*|'') printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")";;
    *) printf '%s' "$1";;
  esac
}
word() {
  SETUP="$SETUP $(quoted "$1")"
  SHOWN="$SHOWN $(quoted "${2-$1}")"
}

# `--adapter`: a program id, `local` or an adapter `steery programs add` added.
set_adapter() {
  case "$1" in
    ''|-*|*[!a-z0-9-]*) refuse "--adapter takes an adapter id such as local, daytona, opensandbox or boat, not $1";;
  esac
  word --adapter; word "$1"
}

# `--setting NAME[=VALUE]`: NAME as an environment variable is named, the value anything
# but a line break. NAME alone must be set here, since setup reads it from the environment
# it inherits; the printed command names it alone, never its value.
add_setting() {
  name="${1%%=*}"
  case "$name" in
    ''|[0-9]*|*[!A-Za-z0-9_]*) refuse "--setting takes NAME or NAME=VALUE, NAME such as DAYTONA_API_KEY, not $name";;
  esac
  case "$1" in
    *=*)
      case "$1" in *'
'*) refuse "the value of --setting $name holds a line break";;
      esac
      VALUED="$VALUED $name"
      word --setting; word "$1" "$name";;
    *)
      if eval "[ -z \"\${$name+x}\" ]"; then
        refuse "--setting $name takes its value from the environment, and $name is not set (export it, or say --setting $name=VALUE)"
      fi
      word --setting; word "$name";;
  esac
}

# `--source`: `image:<ref>` or `snapshot:<name>`, one word with no spaces.
set_source() {
  case "$1" in
    image:?*|snapshot:?*) ;;
    *) refuse "--source takes image:<ref> or snapshot:<name>, not $1";;
  esac
  case "$1" in
    *[[:space:]]*) refuse "--source takes one word, not $1";;
  esac
  word --source; word "$1"
}

# `--harness` values: harness ids, comma-separated.
add_harnesses() {
  case "$1" in
    ''|-*|,*|*,|*,,*|*[!a-z0-9,-]*) refuse "--harness takes harness ids such as omp,claude-code, not $1";;
  esac
  word --harness; word "$1"
}

# `--program` values: one source each, a URL or a path, as one word.
add_program() {
  case "$1" in
    ''|-*|*' '*|*'	'*|*'
'*|*"'"*|*'"'*|*'`'*|*'$'*|*';'*|*'|'*|*'&'*) refuse "--program takes one source, a URL or a path, not $1";;
  esac
  PROGRAMS="$PROGRAMS $1"
}

set_cpu() {
  case "$1" in
    ''|*[!0-9]*) refuse "--cpu takes a percent from 1 to 100, not $1";;
  esac
  if [ "$1" -lt 1 ] || [ "$1" -gt 100 ]; then
    refuse "--cpu takes a percent from 1 to 100, not $1"
  fi
  word --cpu; word "$1"
}

# `--custody`: setup's own choice, `auto` or `file`, passed on as it was said.
set_custody() {
  case "$1" in
    auto|file) word --custody; word "$1";;
    *) refuse "--custody takes auto or file, not $1";;
  esac
}

while [ $# -gt 0 ]; do
  case "$1" in
    --harness) need $# "--harness needs harness ids"; add_harnesses "$2"; shift 2;;
    --harness=*) add_harnesses "${1#--harness=}"; shift;;
    --install) word --install; shift;;
    --program) need $# "--program needs a source"; add_program "$2"; shift 2;;
    --program=*) add_program "${1#--program=}"; shift;;
    --no-default-programs) DEFAULT_PROGRAMS=""; shift;;
    --to) need $# "--to needs a directory"; DEST="$2"; DEST_SAID=1; shift 2;;
    --to=*) DEST="${1#--to=}"; DEST_SAID=1; shift;;
    --install-only) INSTALL_ONLY=1; shift;;
    --join) JOIN=1; INSTALL_ONLY=1; shift;;
    --no-color) NO_COLOR_FLAG=1; shift;;
    --cpu) need $# "--cpu needs a percent"; set_cpu "$2"; shift 2;;
    --cpu=*) set_cpu "${1#--cpu=}"; shift;;
    --custody) need $# "--custody needs auto or file"; set_custody "$2"; shift 2;;
    --custody=*) set_custody "${1#--custody=}"; shift;;
    --no-service) word --no-service; shift;;
    --adapter) need $# "--adapter needs an adapter id"; set_adapter "$2"; shift 2;;
    --adapter=*) set_adapter "${1#--adapter=}"; shift;;
    --setting) need $# "--setting needs NAME or NAME=VALUE"; add_setting "$2"; shift 2;;
    --setting=*) add_setting "${1#--setting=}"; shift;;
    --source) need $# "--source needs image:<ref> or snapshot:<name>"; set_source "$2"; shift 2;;
    --source=*) set_source "${1#--source=}"; shift;;
    --help|-h) usage; drain; exit 0;;
    *) refuse "unknown argument: $1 (see --help)";;
  esac
done
# Setup keeps its folders under HOME, and the default install directory is in it.
[ -n "${HOME:-}" ] || refuse "HOME is not set, so there is no home to install into or set up (set HOME)"
if [ "$DEST_SAID" -eq 0 ]; then DEST="${STEERY_BIN:-$HOME/.local/bin}"; fi
case "$DEST" in
  ''|*'
'*) refuse "invalid install directory";;
esac

# ── what this terminal can draw ───────────────────────────────────────────────
#
# Asked once, answered by what the terminal says about itself, and never guessed
# past that: a run that cannot prove colour prints text, which is the same
# information without the decoration. Everything below is drawn on stderr, so a
# caller redirecting stdout still watches the install, and stdout carries only
# the one line an agent parses.

UI=1                       # is anyone watching stderr
COLOR=0                    # how many colours: 0, 16, 256, or 16777216
GLYPH=0                    # 1 when the terminal is UTF-8 and can draw the art
COLS=80

if [ ! -t 2 ]; then UI=0; fi
if [ "$UI" -eq 1 ] && command -v tput >/dev/null 2>&1; then
  WIDE="$(tput cols 2>/dev/null || echo)"
  case "$WIDE" in
    ''|*[!0-9]*) ;;
    *) if [ "$WIDE" -ge 20 ]; then COLS="$WIDE"; fi;;
  esac
fi

# NO_COLOR is honoured as its own convention states: set at all, to anything.
if [ "$UI" -eq 1 ] && [ "$NO_COLOR_FLAG" -eq 0 ] && [ -z "${NO_COLOR+x}" ]; then
  case "${TERM:-dumb}" in
    dumb|'') ;;
    *)
      DEPTH="$(command -v tput >/dev/null 2>&1 && tput colors 2>/dev/null || echo 0)"
      case "$DEPTH" in *[!0-9]*|'') DEPTH=0;; esac
      if [ "$DEPTH" -ge 8 ]; then COLOR=16; fi
      if [ "$DEPTH" -ge 256 ]; then COLOR=256; fi
      # A terminal that says it paints in 24 bits is taken at its word; nothing
      # else reports these, and a terminal that lies renders the nearest thing.
      case "${COLORTERM:-}" in truecolor|24bit) COLOR=16777216;; esac
      case "${TERM:-}" in *-direct*) COLOR=16777216;; esac
      ;;
  esac
fi

# The art is half-blocks, so it needs UTF-8 and something better than 16 colours
# to be the dog rather than a smear.
if [ "$COLOR" -ge 256 ]; then
  CHARSET="${LC_ALL:-${LC_CTYPE:-${LANG:-}}}"
  case "$CHARSET" in *UTF-8*|*utf8*|*UTF8*|*utf-8*) GLYPH=1;; esac
fi

if [ "$COLOR" -ge 16 ]; then
  R='\033[0m'; B='\033[1m'; DIM='\033[2m'
else
  R=''; B=''; DIM=''
fi
# The colours `steery` paints with too: brand/tokens.json's `terminal`, as SGR parameters.
# >>> generated by brand/tokens.mjs — do not edit by hand
GOLD_16='33'; GOLD_256='38;5;179'
OK_16='32'; OK_256='38;5;71'
ERR_16='31'; ERR_256='38;5;131'
# <<< generated by brand/tokens.mjs
if [ "$COLOR" -ge 256 ]; then
  GOLD="\033[${GOLD_256}m"; OK="\033[${OK_256}m"; ERR="\033[${ERR_256}m"
elif [ "$COLOR" -ge 16 ]; then
  GOLD="\033[${GOLD_16}m"; OK="\033[${OK_16}m"; ERR="\033[${ERR_16}m"
else
  GOLD=''; OK=''; ERR=''
fi

if [ "$GLYPH" -eq 1 ]; then
  TICK='✓'; CROSS='✗'; DOT='·'; BAR='│'; FULL='█'; EMPTY='░'
  FRAMES='⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏'
else
  TICK='ok'; CROSS='XX'; DOT='-'; BAR='|'; FULL='#'; EMPTY='.'
  FRAMES='- \ | /'
fi

say() { [ "$UI" -eq 1 ] && printf "$@" >&2 || true; }
# What a person or an agent needs to read whether or not a terminal watches: a cause, a
# warning. Only the art and the spinner are for a terminal.
note() { printf "$@" >&2; }

# ── the dog ───────────────────────────────────────────────────────────────────
#
# Generated from the brand SVG masters by brand/generate.mjs: a palette of RGB
# triples and one hex digit per half-pixel, index 0 meaning the terminal's own
# background. Regenerate rather than editing — the SVG is the only geometry
# Steery has, and a drawing that drifts from it is a second dog.
# >>> generated by brand/generate.mjs — do not edit by hand
STEERY_ART_PALETTE='33332d 807258 b38042 bd8944 d49e49 d8a24a d8a34b c9b99a e9ca95 f8ecd3'
STEERY_ART_COLS=32
STEERY_ART='0000000000000000000007067676666666667666660600000000000000000000 0000000000000003066666666666666666666666666666660403000000000000 0000000333333446666666666666666666666666666666665634333303000000 0003333333336666666666666666666666666666666666666656333333330000 0033333333446666666666666666666666666666666666666666443333333300 3333333333456666666662616566666666666665616266666666553333333303 3333333333546666664612123666666666666635121246666666443333333333 3333333333446666666666666769696a6a696966666666666666443333333333 33333333334366666666699aaaaaaaaaaaaaaaaa9a6966666666433333333333 33333333333354666669aaaaaa812121212181aaaaaa77666644333333333333 00333333333333646699aaaaaa121111111112aaaaaa99666433333333333330 00333333333333335496aaaaaaa8aa2822aaa8aaaaaa96643333333333333300 0000333333333333335376a6a92a2a1a2a2a2aa9a69640333333333333330000 0000003033333333300000606666769676766760600000303333333330000000'
# <<< generated by brand/generate.mjs

art() {
  [ "$GLYPH" -eq 1 ] || return 0
  [ -n "$STEERY_ART" ] || return 0
  [ "$COLS" -ge "$((STEERY_ART_COLS + 4))" ] || return 0
  awk -v palette="$STEERY_ART_PALETTE" -v rows="$STEERY_ART" -v truecolor="$([ "$COLOR" -gt 256 ] && echo 1 || echo 0)" '
    function hex(s,   i, v) {
      v = 0
      for (i = 1; i <= length(s); i++) v = v * 16 + index("0123456789abcdef", tolower(substr(s, i, 1))) - 1
      return v
    }
    # The 6×6×6 cube xterm-256 lays out above its 16 system colours, with the
    # 24-step grey ramp for anything close to neutral — which is where a cube
    # of six levels is most obviously wrong.
    function level(v) { return v < 48 ? 0 : (v < 115 ? 1 : int((v - 35) / 40)) }
    function xterm(r, g, b,   m, n) {
      m = r < g ? (r < b ? r : b) : (g < b ? g : b)
      n = r > g ? (r > b ? r : b) : (g > b ? g : b)
      if (n - m < 12) return 232 + int(((r + g + b) / 3) * 23 / 255 + 0.5)
      return 16 + 36 * level(r) + 6 * level(g) + level(b)
    }
    function fg(i) { return truecolor ? "\033[38;2;" R[i] ";" G[i] ";" B[i] "m" : "\033[38;5;" X[i] "m" }
    function bg(i) { return truecolor ? "\033[48;2;" R[i] ";" G[i] ";" B[i] "m" : "\033[48;5;" X[i] "m" }
    BEGIN {
      n = split(palette, p, " ")
      for (i = 1; i <= n; i++) {
        R[i] = hex(substr(p[i], 1, 2)); G[i] = hex(substr(p[i], 3, 2)); B[i] = hex(substr(p[i], 5, 2))
        X[i] = xterm(R[i], G[i], B[i])
      }
      split(rows, line, " ")
      for (y = 1; y in line; y++) {
        out = "  "
        # Escapes are emitted only where a colour changes, so one flat row of
        # coat costs one escape rather than one per cell.
        top = -1; bottom = -1
        for (c = 1; c <= length(line[y]) / 2; c++) {
          t = hex(substr(line[y], c * 2 - 1, 1)); b = hex(substr(line[y], c * 2, 1))
          if (t == 0 && b == 0) { out = out "\033[0m "; top = -1; bottom = -1; continue }
          if (t == 0) {
            if (bottom != -1) { out = out "\033[0m"; top = -1; bottom = -1 }
            if (top != b) { out = out fg(b); top = b }
            out = out "▄"
            continue
          }
          if (b == 0) {
            # A reset clears the foreground as well as the background, so the
            # remembered foreground goes with it. Forgetting that leaves the
            # next cell drawn in whatever colour the terminal defaults to.
            if (bottom != -1) { out = out "\033[0m"; bottom = -1; top = -1 }
            if (top != t) { out = out fg(t); top = t }
            out = out "▀"
            continue
          }
          if (top != t) { out = out fg(t); top = t }
          if (bottom != b) { out = out bg(b); bottom = b }
          out = out "▀"
        }
        print out "\033[0m"
      }
    }
  ' >&2
}

# ── steps ─────────────────────────────────────────────────────────────────────
#
# One line per step. At a terminal it spins while the step runs and is rewritten
# in place when it settles, so the screen holds the state of the install rather
# than a scroll of what it used to be. Anywhere else the same facts are appended,
# one line each, which is what a log wants.

SPIN_PID=''
SPIN_REST=''
FRAME=''
STEP=''

# The next spinner frame, rotating. Held as the unconsumed tail of the frame
# list rather than an index, because `sh` has no arrays and indexing a string of
# multi-byte glyphs by character is exactly the thing that breaks outside C.
next_frame() {
  if [ -z "$SPIN_REST" ]; then SPIN_REST="$FRAMES"; fi
  FRAME="${SPIN_REST%% *}"
  case "$SPIN_REST" in
    *' '*) SPIN_REST="${SPIN_REST#* }";;
    *) SPIN_REST='';;
  esac
}

hide_cursor() { [ "$UI" -eq 1 ] && printf '\033[?25l' >&2 || true; }
show_cursor() { [ "$UI" -eq 1 ] && printf '\033[?25h' >&2 || true; }
clear_line() { [ "$UI" -eq 1 ] && printf '\r\033[K' >&2 || true; }

spin_stop() {
  [ -n "$SPIN_PID" ] || return 0
  kill "$SPIN_PID" 2>/dev/null || true
  wait "$SPIN_PID" 2>/dev/null || true
  SPIN_PID=''
  clear_line
}

# A step that starts while another spins takes its line: one spinner at a time.
step() {
  spin_stop
  STEP="$1"
  if [ "$UI" -eq 0 ] || [ "$COLOR" -eq 0 ]; then
    if [ "$UI" -eq 1 ]; then printf '  %s %s\n' "$DOT" "$STEP" >&2; fi
    return 0
  fi
  (
    while :; do
      for f in $FRAMES; do
        printf "\r\033[K  ${GOLD}%s${R} %s" "$f" "$STEP" >&2
        sleep "$TICK_SECS" 2>/dev/null || sleep 1
      done
    done
  ) &
  SPIN_PID=$!
}

# A settled step: mark, name, and the one fact worth keeping about it.
settle() {
  spin_stop
  [ "$UI" -eq 1 ] || return 0
  printf "  ${OK}%s${R} %-22s ${DIM}%s${R}\n" "$TICK" "$1" "${2:-}" >&2
}

# Every failure leaves through here: the mark, what failed, and — because this
# script replaces a binary people depend on — what it did not touch.
die() {
  spin_stop
  show_cursor
  printf "\n  ${ERR}%s %s${R}\n" "$CROSS" "$1" >&2
  shift
  for line in "$@"; do
    printf "    ${ERR}${BAR}${R} ${DIM}%s${R}\n" "$line" >&2
  done
  printf '\n' >&2
  exit 1
}

rule() { say "  ${DIM}%s${R}\n" "$(awk -v n="$((COLS - 4))" -v c="$([ "$GLYPH" -eq 1 ] && echo '─' || echo '-')" 'BEGIN{while(i++<n)s=s c;print s}')"; }

TICK_SECS=0.08
sleep "$TICK_SECS" 2>/dev/null || TICK_SECS=1

# What an exit leaves behind is cleared here, and what this script exits with is 0 or 1:
# anything else — the shell's own failure, a command that was not there — is reported and
# becomes 1. 130 and 143 are an interrupt and a termination, which stay as they are.
TMP=""
# A set being staged, until the link names it, and the link being made: both gone if
# this stops before the switch.
STAGE=""
LINK=""
trap 'e=$?; spin_stop; show_cursor; if [ -n "$TMP" ]; then rm -rf "$TMP"; fi; if [ -n "$STAGE" ]; then rm -rf "$STAGE"; fi; if [ -n "$LINK" ]; then rm -f "$LINK"; fi; case "$e" in 0|1|130|143) ;; *) printf "install.sh: stopped unexpectedly (status %s)\n" "$e" >&2; e=1;; esac; exit $e' EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

# `mkdir -p`, or a die box naming why.
make_dir() {
  if ! mkdir -p "$1" 2>"$TMP/mkdir.err"; then
    CAUSE="$(tail -n 1 "$TMP/mkdir.err" 2>/dev/null | cut -c1-300)"
    die "Could not create $1" ${CAUSE:+"$CAUSE"} "Nothing was installed."
  fi
}

OS="$(uname -s)"
ARCH="$(uname -m)"
if [ "$JOIN" -eq 1 ] && [ "$OS" != Linux ]; then
  die "--join is for Linux hosts" "A computer of yours sets up with \`steery setup\` instead."
fi
case "$OS" in
  Darwin)
    case "$ARCH" in
      arm64) TARGET="aarch64-apple-darwin";;
      x86_64) TARGET="x86_64-apple-darwin";;
      *) die "Unsupported macOS architecture: $ARCH" "Steery ships for arm64 and x86_64.";;
    esac
    ;;
  Linux)
    # No C library version is written here: which one a build needs is the build's own
    # fact, and running it ("Running what was downloaded", below) is the one ground truth.
    case "$ARCH" in
      x86_64|amd64) TARGET="x86_64-unknown-linux-gnu";;
      aarch64|arm64) TARGET="aarch64-unknown-linux-gnu";;
      *) die "Unsupported Linux architecture: $ARCH" "Steery ships for x86_64 and aarch64.";;
    esac
    ;;
  *) die "Unsupported OS: $OS" "The steery CLI ships for macOS and Linux only.";;
esac

if command -v curl >/dev/null 2>&1; then
  fetch() { curl -fsSL --retry 3 --proto '=https' --tlsv1.2 -o "$2" "$1" 2>"$TMP/fetch.err"; }
  # The length the server states, for the progress bar. A server that will not
  # say is not pressed: the bar becomes a byte counter, which is the honest
  # shape of "downloading, total unknown".
  length() { curl -fsSLI --retry 1 --proto '=https' --tlsv1.2 "$1" 2>/dev/null | awk 'tolower($1) == "content-length:" { gsub(/\r/, "", $2); n = $2 } END { print n + 0 }'; }
elif command -v wget >/dev/null 2>&1; then
  fetch() { wget -nv --https-only -O "$2" "$1" 2>"$TMP/fetch.err"; }
  length() { wget -q --https-only --spider --server-response "$1" 2>&1 | awk 'tolower($1) == "content-length:" { gsub(/\r/, "", $2); n = $2 } END { print n + 0 }'; }
else
  die "Need curl or wget" "Install either one and run this again."
fi
# The last line the failed fetch said, for the die box.
why() { tail -n 1 "$TMP/fetch.err" 2>/dev/null | tr -d '\r' | cut -c1-300; }

if command -v sha256sum >/dev/null 2>&1; then
  sha256() { sha256sum "$1" | cut -d' ' -f1; }
elif command -v shasum >/dev/null 2>&1; then
  sha256() { shasum -a 256 "$1" | cut -d' ' -f1; }
else
  die "Need sha256sum or shasum" "The archive is not installed without verifying its checksum."
fi
command -v tar >/dev/null 2>&1 || die "Need tar" "Install tar and run this again."
command -v awk >/dev/null 2>&1 || die "Need awk" "Install awk and run this again."

TMP="$(mktemp -d)" || die "Could not make a temporary folder" "Check that TMPDIR (${TMPDIR:-/tmp}) exists and is yours." "Nothing was installed."

say '\n'
art
say "\n  ${B}${GOLD}Steery${R}\n"
say "  ${DIM}Your agents keep working. Decisions come to you.${R}\n\n"

hide_cursor

# Resolve the fixed latest pointer to a versioned archive name. The pointer
# content is treated as data (a filename), never executed or eval'd.
step "Resolving the current build for $TARGET"
fetch "$BASE/steery-$TARGET.latest" "$TMP/pointer" || { CAUSE="$(why)"; die "Could not reach $BASE" ${CAUSE:+"$CAUSE"} "Check the network and run this again." "Nothing was installed."; }
ARCHIVE="$(tr -d ' \t\r\n' < "$TMP/pointer")"
case "$ARCHIVE" in
  "steery-"*"-${TARGET}.tar.gz") ;;
  *) die "Malformed latest pointer for $TARGET" "Nothing was installed.";;
esac
case "$ARCHIVE" in
  *'..'*|*"/"*|*"'"*|*'"'*|*"\`"*|*'$'*|*'&'*|*';'*|*'|'*|*'*'*)
    die "Unsafe archive name in the latest pointer" "Nothing was installed.";;
esac
URL="$BASE/$ARCHIVE"

# The archive is named by the build it holds, and so is the binary: `steery --version`
# prints the same string. It is installed whether or not they agree: a binary that says
# the right version is not evidence that its bytes are the published ones, and the cost
# of being sure is one download.
VERSION="${ARCHIVE#steery-}"
VERSION="${VERSION%-"${TARGET}".tar.gz}"
INSTALLED=""
if [ -x "$DEST/steery" ]; then
  INSTALLED="$("$DEST/steery" --version 2>/dev/null | cut -d' ' -f2-)"
fi
if [ -n "$INSTALLED" ] && [ "$INSTALLED" != "$VERSION" ]; then
  settle "Version" "$VERSION  (was $INSTALLED)"
else
  settle "Version" "$VERSION"
fi

# ── the download, with the bar the bytes actually justify ─────────────────────

TOTAL="$(length "$URL")"
case "$TOTAL" in *[!0-9]*|'') TOTAL=0;; esac

human() { awk -v b="$1" 'BEGIN { if (b >= 1048576) printf "%.1f MB", b / 1048576; else if (b >= 1024) printf "%.0f kB", b / 1024; else printf "%d B", b }'; }
# The bytes in so far, and their rate since the download began; nothing in the first second.
speed() { if [ "$2" -gt 0 ]; then printf '%s/s' "$(human $(( $1 / $2 )))"; fi; }
# The bytes in so far: the file curl or wget writes, which is not there until the body starts.
got() {
  GOT=0
  if [ -f "$TMP/$ARCHIVE" ]; then
    GOT="$(wc -c < "$TMP/$ARCHIVE" 2>/dev/null | tr -d ' ' || echo 0)"
    case "$GOT" in *[!0-9]*|'') GOT=0;; esac
  fi
}

# STEERY_STEPS=1 is a program showing these lines live (the Mac app): with no terminal to
# draw a bar on, the download is said once a second as one plain line it reads.
STEPS=0
if [ "${STEERY_STEPS:-}" = 1 ]; then STEPS=1; fi

if [ "$UI" -eq 1 ] && [ "$COLOR" -gt 0 ]; then
  fetch "$URL" "$TMP/$ARCHIVE" & FETCH_PID=$!
  BEGAN="$(date +%s)"
  WIDTH=$((COLS - 52))
  if [ "$WIDTH" -gt 28 ]; then WIDTH=28; fi
  if [ "$WIDTH" -lt 8 ]; then WIDTH=8; fi
  while kill -0 "$FETCH_PID" 2>/dev/null; do
    got
    RATE="$(speed "$GOT" $(( $(date +%s) - BEGAN )))"
    next_frame
    if [ "$TOTAL" -gt 0 ]; then
      printf "\r\033[K  ${GOLD}%s${R} %-14s ${GOLD}%s${R}${DIM}%s${R}  %3d%%  ${DIM}%s / %s  %s${R}" \
        "$FRAME" "Downloading" \
        "$(awk -v g="$GOT" -v t="$TOTAL" -v w="$WIDTH" -v c="$FULL" 'BEGIN{n=int(w*g/t);while(i++<n)s=s c;print s}')" \
        "$(awk -v g="$GOT" -v t="$TOTAL" -v w="$WIDTH" -v c="$EMPTY" 'BEGIN{n=w-int(w*g/t);while(i++<n)s=s c;print s}')" \
        "$((GOT * 100 / TOTAL))" "$(human "$GOT")" "$(human "$TOTAL")" "$RATE" >&2
    else
      printf "\r\033[K  ${GOLD}%s${R} %-14s ${DIM}%s  %s${R}" \
        "$FRAME" "Downloading" "$(human "$GOT")" "$RATE" >&2
    fi
    sleep "$TICK_SECS" 2>/dev/null || sleep 1
  done
  wait "$FETCH_PID" || { clear_line; CAUSE="$(why)"; die "Download failed" "$URL" ${CAUSE:+"$CAUSE"} "Nothing was installed."; }
  clear_line
elif [ "$STEPS" -eq 1 ]; then
  fetch "$URL" "$TMP/$ARCHIVE" & FETCH_PID=$!
  BEGAN="$(date +%s)"
  while kill -0 "$FETCH_PID" 2>/dev/null; do
    got
    RATE="$(speed "$GOT" $(( $(date +%s) - BEGAN )))"
    if [ "$TOTAL" -gt 0 ]; then
      printf 'Downloading %d%% · %s of %s%s\n' "$((GOT * 100 / TOTAL))" "$(human "$GOT")" "$(human "$TOTAL")" "${RATE:+ · $RATE}" >&2
    else
      printf 'Downloading %s%s\n' "$(human "$GOT")" "${RATE:+ · $RATE}" >&2
    fi
    sleep 1
  done
  wait "$FETCH_PID" || { CAUSE="$(why)"; die "Download failed" "$URL" ${CAUSE:+"$CAUSE"} "Nothing was installed."; }
else
  step "Downloading $ARCHIVE"
  fetch "$URL" "$TMP/$ARCHIVE" || { CAUSE="$(why)"; die "Download failed" "$URL" ${CAUSE:+"$CAUSE"} "Nothing was installed."; }
fi
settle "Downloaded" "$(human "$(wc -c < "$TMP/$ARCHIVE" | tr -d ' ')")"

step "Verifying the checksum"
fetch "$URL.sha256" "$TMP/$ARCHIVE.sha256" || { CAUSE="$(why)"; die "Could not fetch the checksum" "$URL.sha256" ${CAUSE:+"$CAUSE"} "Nothing was installed."; }

# The sidecar holds "<sha256>  <archive>"; compare hashes as fixed strings.
EXPECTED="$(cut -d' ' -f1 < "$TMP/$ARCHIVE.sha256")"
case "$EXPECTED" in
  ????????????????????????????????????????????????????????????????)
    case "$EXPECTED" in *[!0-9a-fA-F]*) die "Malformed checksum file" "Nothing was installed.";; esac;;
  *) die "Malformed checksum file" "Nothing was installed.";;
esac
ACTUAL="$(sha256 "$TMP/$ARCHIVE")"
if [ "$ACTUAL" != "$EXPECTED" ]; then
  die "Checksum mismatch for $ARCHIVE" \
    "expected  $EXPECTED" \
    "got       $ACTUAL" \
    "The download is corrupt or has been tampered with." \
    "Nothing was installed; the steery you had is untouched."
fi
settle "Checksum" "ok"

# List members verbosely: type flag, then name. On Linux the archive is `steery`, a
# regular file at its top. On macOS it is Steery.app — the signed bundle that carries the
# provisioning profile a Secure Enclave key needs — and `steery`, a symlink into it;
# every member must be inside the bundle or be that one link, and the one executable is
# `steery`. Anything else is refused before extraction: the programs come from their own
# sources below.
step "Checking what the archive contains"
if ! tar -tzvf "$TMP/$ARCHIVE" > "$TMP/listing.txt" 2>"$TMP/tar.err"; then
  CAUSE="$(tail -n 1 "$TMP/tar.err" 2>/dev/null | cut -c1-300)"
  die "The archive is not a valid tarball" ${CAUSE:+"$CAUSE"} "Its checksum matched, so what is published is broken." "Nothing was installed."
fi
CONTENTS=0
# A symlink line ends `name -> target`, so its name is three fields from the end.
awk -v os="$OS" '
  {
    t = substr($1, 1, 1); n = (t == "l") ? $(NF-2) : $NF; sub(/^\.\//, "", n)
    if (n == "") next
    if (os == "Darwin") {
      if (n == "steery" && t == "l" && $NF == "Steery.app/Contents/MacOS/steery") { link = 1; next }
      if (n !~ /^Steery\.app(\/|$)/ || (t != "-" && t != "d")) { bad = 1; next }
      exe = n
      if (!sub(/^Steery\.app\/Contents\/MacOS\//, "", exe) || exe == "") next
      if (t != "-") { bad = 1; next }
    } else {
      if (t != "-" || n ~ /\//) { bad = 1; next }
      exe = n
    }
    if (exe == "steery") steery = 1
    else bad = 1
  }
  END {
    if (bad || !steery || (os == "Darwin" && !link)) exit 1
  }' "$TMP/listing.txt" || CONTENTS=$?
case "$CONTENTS" in
  0) settle "Contents" "steery" ;;
  *) die "Unexpected archive contents" "Nothing was installed." ;;
esac

# Install dir must be owned by the invoking user: never sudo, never chown.
step "Installing to $DEST"
make_dir "$DEST"
case "$OS" in
  Darwin) OWNER="$(stat -f '%u' "$DEST")" || die "Could not read who owns $DEST" "Nothing was installed." ;;
  *) OWNER="$(stat -c '%u' "$DEST")" || die "Could not read who owns $DEST" "Nothing was installed." ;;
esac
if [ "$OWNER" != "$(id -u)" ]; then
  die "$DEST is not yours" \
    "Run this without sudo, and pick a directory you own." \
    "Nothing was installed."
fi
if [ -d "$DEST/steery" ]; then
  die "$DEST/steery is a directory" "Refusing to touch it. Nothing was installed."
fi

# The set is unpacked into a folder of its own under DEST/.steery — the same filesystem
# as the link, so the switch below is one rename — beside whatever set runs now, which
# nothing here touches.
SETS="$DEST/.steery"
make_dir "$SETS"
STAGE="$(mktemp -d "$SETS/.stage-XXXXXX")" || die "Could not make a folder in $SETS" "Nothing was installed."
chmod 755 "$STAGE" || die "Could not set the mode of $STAGE" "Nothing was installed."
# --no-same-owner: as root, tar would keep the archive's owner, and a user of that uid
# here could rewrite the installed steery.
if ! tar --no-same-owner -xzf "$TMP/$ARCHIVE" -C "$STAGE" 2>"$TMP/tar.err"; then
  CAUSE="$(tail -n 1 "$TMP/tar.err" 2>/dev/null | cut -c1-300)"
  die "The archive did not unpack" ${CAUSE:+"$CAUSE"} "Nothing was installed."
fi
case "$OS" in
  Darwin)
    [ -f "$STAGE/Steery.app/Contents/MacOS/steery" ] || die "Archive is missing Steery.app" "Nothing was installed."
    # The signature is what lets the binary keep its key in the Secure Enclave, and
    # what says who built it. A bundle
    # that does not verify is not installed, and there is no way past this: an
    # unsigned steery has no custody to offer. The requirement is the one macOS keeps
    # this Mac's Privacy & Security settings for Steery against, so every version that
    # meets it keeps them; the runtime's own updater checks the same one (update.rs).
    step "Verifying Apple's signature on the bundle"
    SIGNED_AS='identifier "dev.steery.cli" and anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] and certificate leaf[field.1.2.840.113635.100.6.1.13] and certificate leaf[subject.OU] = A87GNG2RAV'
    if ! codesign --verify --strict -R="$SIGNED_AS" "$STAGE/Steery.app" 2>"$TMP/codesign.err"; then
      BY="$(codesign -dvv "$STAGE/Steery.app" 2>&1 | awk -F= '/^Authority=/{print $2; exit}')"
      die "Steery.app is not signed as Steery publishes it (Developer ID, team A87GNG2RAV)" \
        "Signed by ${BY:-nobody}: $(tr '\n' ' ' < "$TMP/codesign.err")" \
        "Nothing was installed."
    fi
    settle "Signature" "Developer ID, team A87GNG2RAV"
    ;;
  *)
    chmod 755 "$STAGE"/*
    ;;
esac

# Run what was downloaded before it is installed: a file cut short, or a build this
# computer cannot run, stops here with the set that was there still the one that runs.
step "Running what was downloaded"
SAID="$("$STAGE/steery" --version 2>"$TMP/run.err" || true)"
if [ "$SAID" != "steery $VERSION" ]; then
  # What the loader or the shell said, the line naming the C library first.
  LOADER="$(awk '/GLIBC/ { print; exit }' "$TMP/run.err" | cut -c1-300)"
  if [ -z "$LOADER" ]; then LOADER="$(awk 'NF { print; exit }' "$TMP/run.err" | cut -c1-300)"; fi
  WHY=""
  if [ "$OS" = Linux ]; then
    LIBC="$(getconf GNU_LIBC_VERSION 2>/dev/null || true)"
    case "$LIBC" in
      'glibc '*)
        case "$LOADER" in
          *GLIBC*) WHY="This computer has $LIBC, older than the C library this build needs (the line above names the version).";;
        esac;;
      *) WHY="This computer has no glibc (a musl system, as Alpine is), and the prebuilt steery needs glibc.";;
    esac
  fi
  die "The downloaded steery does not run here" "It said: ${SAID:-nothing}" ${LOADER:+"The system said: $LOADER"} ${WHY:+"$WHY"} \
    "Nothing was installed; the steery you had is untouched."
fi
settle "Runs here" "steery $VERSION"

# The switch: the set gets its name, then the link DEST/steery is moved onto it in one
# rename. Every steery started after it runs the new set, every one started before it
# the old one, never a mixture.
SET="$VERSION-${STAGE##*/.stage-}"
mv "$STAGE" "$SETS/$SET" || die "Could not move the new set into $SETS" "Nothing was installed."
STAGE="$SETS/$SET"
PREVIOUS="$(readlink "$DEST/steery" 2>/dev/null || true)"
LINK="$(mktemp "$DEST/.steery-link-XXXXXX")" || die "Could not make a link in $DEST" "Nothing was installed; the steery you had is untouched."
rm -f "$LINK"
ln -s ".steery/$SET/steery" "$LINK" || die "Could not link the new set" "Nothing was installed; the steery you had is untouched."
mv -f "$LINK" "$DEST/steery" || die "Could not move the link onto $DEST/steery" "Nothing was installed; the steery you had is untouched."
LINK=""
STAGE=""
settle "Installed" "$DEST/steery"

# The drivers and adapters, each from its own source, as any program is added: a source
# added before is brought up to its latest release, and one this run does not name is
# kept. Nothing is asked: running this is choosing them. A source that cannot be read
# is said with its cause and the others are still tried; the run then ends with exit 1
# naming it (below), because a steery with no drivers and no adapter cannot be set up.
STEERY="$DEST/steery"
# The one way a command of this machine's own is shown: in double quotes, or — where the
# path holds a quote, a dollar, a backtick or a backslash — as setup's words are.
case "$STEERY" in
  *'"'*|*'$'*|*'`'*|*'\'*|*"'"*) STEERY_Q="$(quoted "$STEERY")";;
  *) STEERY_Q="\"$STEERY\"";;
esac
# A host that joins runs `serve` from its set, and a set's programs are the ones in
# `programs/` beside its `steery` (as a made host's set carries them), so --join adds them
# there; anything else adds them to this computer's own.
INTO=""
if [ "$JOIN" -eq 1 ]; then
  INTO="$SETS/$SET/programs"
fi
FAILED=""
FAILED_WHY=""
add_programs() {
  step "Adding the programs of $1"
  if STEERY_PROGRAMS_DIR="$INTO" "$STEERY" programs add --yes $2 > "$TMP/programs.txt" 2>&1; then
    settle "Programs" "$1"
  else
    spin_stop
    note "  ${GOLD}%s${R} %s\n" "$DOT" "Could not add the programs of $1"
    sed 's/^/    /' "$TMP/programs.txt" >&2
    FAILED="$FAILED${FAILED:+, }$1"
    FAILED_WHY="$(awk 'NF { l = $0 } END { print substr(l, 1, 300) }' "$TMP/programs.txt")"
  fi
}
# Steery's own: `steery programs add` with no source adds them, from the list it keeps.
if [ -n "$DEFAULT_PROGRAMS" ]; then add_programs "Steery" ""; fi
for SOURCE in $PROGRAMS; do
  add_programs "$SOURCE" "$SOURCE"
done

# The set before stays for whatever still runs it. Every other set, and any stage left
# by an install that stopped, is cleared once nothing has written to it for an hour:
# another install may be about to name it. On macOS a set a live process runs from stays
# whatever its age (a turn's anchor runs from the set that was current when its session
# began), and where the processes cannot be listed nothing is cleared this time. This is
# the rule machine/install.rs follows too; the runtime's own updater (update.rs) has no live-process exception.
case "$PREVIOUS" in
  .steery/*/*) KEEP="${PREVIOUS#.steery/}"; KEEP="${KEEP%%/*}" ;;
  *) KEEP="" ;;
esac
LIVE="$TMP/live.txt"
: > "$LIVE"
PRUNE=1
if [ "$OS" = Darwin ]; then ps -axo comm= > "$LIVE" 2>/dev/null || PRUNE=0; fi
if [ "$PRUNE" -eq 1 ]; then
  find "$SETS" -mindepth 1 -maxdepth 1 -mmin +60 | while IFS= read -r OLD; do
    case "${OLD##*/}" in
      "$SET"|"$KEEP") ;;
      *) if ! grep -qF "/.steery/${OLD##*/}/" "$LIVE"; then rm -rf "$OLD"; fi ;;
    esac
  done
fi

# Whatever was serving this install before — an older runtime, one the app started, one
# left stopped — is replaced by the binary just installed, so nothing keeps answering with
# an older catalog. Only a service whose program is DEST/steery is this install's: one
# into another folder (`--to`) leaves the runtime this computer serves from as it is.
# Failing here is never fatal: setup installs the unit again.
case "$OS" in
  Darwin)
    SERVICE="gui/$(id -u)/dev.steery.run"
    if [ "$(launchctl print "$SERVICE" 2>/dev/null | awk '$1 == "program" && $2 == "=" { print $3; exit }')" = "$DEST/steery" ]; then
      launchctl kickstart -k "$SERVICE" >/dev/null 2>&1 || true
    fi
    ;;
  *)
    if command -v systemctl >/dev/null 2>&1 && systemctl --user is-enabled dev.steery.run.service >/dev/null 2>&1; then
      case "$(systemctl --user show dev.steery.run.service -p ExecStart --value 2>/dev/null)" in
        *"path=$DEST/steery "*) systemctl --user restart dev.steery.run.service >/dev/null 2>&1 || true ;;
      esac
    fi
    ;;
esac

# A steery with no drivers or adapters cannot be set up, and saying "next:" as though it
# could is what sent an agent into a setup that failed on `no driver for it here`. Setup
# adds Steery's own two sources again when it runs and finds them missing
# (`programs::add_missing_defaults`), but it only says what it could not add; it cannot
# do better than this run could.
if [ -n "$FAILED" ]; then
  die "The programs of $FAILED were not added" ${FAILED_WHY:+"$FAILED_WHY"} \
    "steery is installed at $DEST/steery; its drivers and adapters are not, and setup needs them." \
    "Run this again once the network is back, or add them with $STEERY_Q programs add --yes [<source>]."
fi

show_cursor

case ":$PATH:" in
  *":$DEST:"*) ;;
  *)
    note "\n  ${GOLD}%s${R} %s\n" "$DOT" "$DEST is not on your PATH"
    note "    ${DIM}add: export PATH=\"%s:\$PATH\"${R}\n" "$DEST"
    note "    ${DIM}until then run it as %s${R}\n" "$STEERY_Q"
    ;;
esac

# The command that finishes everything. With nothing stated here it is shown bare, which
# is what makes `steery setup` ask what runs the work here and list every harness. It is
# SHOWN, never SETUP: a setting given as NAME=VALUE is printed as NAME alone, which setup
# reads from the environment, so the value is never on the screen or in a log.
SETUP_HINT="setup$SHOWN"
# Settings whose value was on this command line, and so is not in the environment the
# printed command will run in.
ENV_NOTE=""
if [ -n "$VALUED" ]; then
  ENV_NOTE="with$VALUED exported as you gave it here"
fi
if [ "$JOIN" -eq 1 ]; then
  # Joining is Linux's: a host of a system's own. Its token is the system's secret, given
  # to each host when it starts, so an image being built has none and gets the command.
  if [ -z "${STEERY_JOIN:-}" ]; then
    say "\n  ${DIM}Installed. Each host joins once it starts, with STEERY_JOIN set:${R}\n\n"
    say "    ${B}%s host join${R}\n\n" "$STEERY_Q"
    echo "next: STEERY_JOIN=… $STEERY_Q host join"
    exit 0
  fi
  LOGS="${XDG_CONFIG_HOME:-$HOME/.config}/steery/logs"
  make_dir "$LOGS"
  nohup "$STEERY" host join >> "$LOGS/join.log" 2>&1 < /dev/null &
  JOINING=$!
  # What it prints first is where omp's extension is, for a system that runs omp with
  # --no-extensions (§4.3). Waited for 10 s, or until the join has ended.
  TRIES=0
  while [ "$TRIES" -lt 50 ] && ! grep -q '^omp extension:' "$LOGS/join.log" 2>/dev/null && kill -0 "$JOINING" 2>/dev/null; do
    sleep 0.2
    TRIES=$((TRIES + 1))
  done
  if grep -q '^omp extension:' "$LOGS/join.log" 2>/dev/null; then
    grep '^omp extension:' "$LOGS/join.log" | tail -1
  elif ! kill -0 "$JOINING" 2>/dev/null; then
    # A host join runs for as long as the host does: one that ended did not join.
    die "steery host join stopped at once" "$(tail -n 1 "$LOGS/join.log" 2>/dev/null | cut -c1-300)" "Its log: $LOGS/join.log"
  else
    note "  %s\n" "No omp extension line in 10 s (a system that runs no omp has none); host join is still running, its log $LOGS/join.log"
  fi
  echo "joining: $STEERY_Q host join, its log $LOGS/join.log"
  exit 0
fi
if [ "$INSTALL_ONLY" -eq 1 ]; then
  say '\n'
  rule
  say "\n  ${DIM}The binary and its programs are on disk and configure nothing. Next:${R}\n\n"
  say "    ${B}%s %s${R}\n\n" "$STEERY_Q" "$SETUP_HINT"
  if [ -n "$ENV_NOTE" ]; then say "    ${DIM}%s${R}\n\n" "$ENV_NOTE"; fi
  # stdout, because this is the line a caller parses.
  echo "next: $STEERY_Q $SETUP_HINT"
  exit 0
fi

# A person is only assumed present when there is a terminal to ask questions on.
# CI is detected, never guessed at: a runner has no terminal, and $CI is the one
# variable every hosted runner sets.
INTERACTIVE=1
[ -t 1 ] || INTERACTIVE=0
case "${CI:-}" in ''|0|false|False|FALSE) ;; *) INTERACTIVE=0;; esac

# Under `curl | sh` the shell's stdin is this script, so setup's questions are read
# from the controlling terminal: this redirects it, and setup opens it itself when a
# caller does not. Setup asks what runs the work here (this computer, or an adapter's
# hosts and that adapter's settings) unless --adapter said, which harnesses (installing a
# missing one you pick, once you said yes to its installer), signs in the first time,
# creates this machine's key or finds it, checks everything it did, ends with one
# question on the phone. Every one of
# the questions needs the person who ran this; on a machine set up before, only the
# harnesses and the last question are asked, and what runs the work stays as it was.
# SETUP is run through `eval` because each word in it is quoted for exactly that.
# How a run of `steery setup` ends this script, whichever branch ran it: 0 is done; 2 is a
# step of the person's still pending, which setup said in its own words, so nothing is
# drawn as a failure and the same command is printed as `next:` for whoever runs it again,
# and the exit is 1; anything else is a failure, said in a box.
setup_ended() {
  case "$1" in
    0) exit 0;;
    2)
      echo "next: $STEERY_Q $SETUP_HINT"
      exit 1;;
    *) die "Setup did not finish" "$2" ${ENV_NOTE:+"$ENV_NOTE"};;
  esac
}
# /dev/tty is opened to see whether it can be: the node is readable by everyone, but a
# process with no controlling terminal (an agent's pty, `setsid`) cannot open it, and a
# redirect that fails would end the script with the shell's own status. When it cannot be
# opened this is a run with nobody there.
if [ "$INTERACTIVE" -eq 1 ] && ( : </dev/tty ) 2>/dev/null; then
  say '\n'
  rule
  say "\n  ${B}Setup${R}  ${DIM}choose the harnesses here, then sign in${R}\n"
  # The dog is already on the screen a few lines up; setup draws its own when it
  # is the top of the flow, and here it is not.
  export STEERY_NO_BANNER=1
  SETUP_RC=0
  eval "\"\$STEERY\" setup$SETUP" </dev/tty || SETUP_RC=$?
  setup_ended "$SETUP_RC" "Run again: $STEERY_Q $SETUP_HINT"
fi

# Nobody is here. A machine that is set up has a key, and setup on it needs nobody: it
# keeps what is set up — or has exactly what was named — brings it up to this binary,
# keeps the key, restarts the runtime and checks all of it. That is the
# whole of an unattended upgrade.
if [ -r "${XDG_CONFIG_HOME:-$HOME/.config}/steery/key.json" ]; then
  SETUP_RC=0
  eval "\"\$STEERY\" setup$SETUP" || SETUP_RC=$?
  setup_ended "$SETUP_RC" "Run $STEERY_Q $SETUP_HINT to see why."
fi

say '\n'
rule
say "\n  ${GOLD}%s${R} ${B}steery is installed, and nothing else has been done.${R}\n\n" "$DOT"
say "    ${DIM}Choosing what runs the work here and which harnesses to configure,${R}\n"
say "    ${DIM}and signing in, need you.${R}\n\n"
say "  ${DIM}To finish, at a terminal:${R}\n\n"
say "    ${B}%s %s${R}\n\n" "$STEERY_Q" "$SETUP_HINT"
if [ -n "$ENV_NOTE" ]; then say "    ${DIM}%s${R}\n\n" "$ENV_NOTE"; fi
say "  ${DIM}An agent finishes it by https://steery.dev/install.md, with no terminal.${R}\n\n"
echo "next: $STEERY_Q $SETUP_HINT"
exit 0
