#!/bin/sh
# @generated by scripts/generate-install.sh; edit scripts/installer/*.sh instead.
# Install phux, and with --rune Phux Rune, from a verified release
# (ADR-0176). Served verbatim at https://phux.sh/install. POSIX sh: Debian and
# Ubuntu pipe it to dash, which rejects `set -o pipefail` and `printf %q`.
set -eu

RELEASES=https://github.com/no-phux/phux/releases/download
# minisign keys a release checksum may be signed by (ADR-0178): current
# (9F105950F46456C9), then next (B9E437599627DC6A). One line, kept equal to
# RELEASE_KEYS in crates/phux-client-runtime/src/release/signature.rs by a test.
RELEASE_KEYS='RWTJVmT0UFkQn2Zw1mG2cIcm5O/9kLuffefLpHw3vwhWAxgn/gcsoxiX RWRq3CeWWTfkuYUoONcL0LsC/L3BYav/SIeHRPDMauxHAZnrUd+UoYU1'

phux_message() (
  label="$1"
  shift
  if [ -z "${NO_COLOR:-}" ] && [ "${TERM:-}" != dumb ] && [ -t 2 ]; then
    case "$label" in error) style=31 ;; warn) style=33 ;; ok) style=32 ;; *) style=36 ;; esac
    printf '\033[1mphux\033[0m: \033[%sm%s\033[0m: %s\n' "$style" "$label" "$*" >&2
  else
    printf 'phux: %s: %s\n' "$label" "$*" >&2
  fi
)
die() {
  phux_message error "$*"
  exit 1
}
# A step worth knowing about only with --verbose: versions, places, checks.
detail() {
  [ "${verbose:-0}" -eq 0 ] || phux_message "$@"
}

usage() {
  cat <<'EOF'
Usage: curl -fsSL https://phux.sh/install | sh -s -- [options]

Installs phux and phux-mcp. With --rune, installs Phux Rune, the desktop
app (Apple silicon macOS 14+, or x86_64 or arm64 GNU/Linux), and the CLI
only when none is found.

  --channel <stable|latest|next|lts>
                                  Release channel (default: stable, or $PHUX_CHANNEL).
                                  lts is the promoted long-term-support release.
  --version <X.Y.Z>               Pin a stable release (vX.Y.Z also accepted).
  --revision <sha>                Pin a next build by its 40-character commit.
  --sha256 <hex>                  Expected digest of a pinned artifact, instead of its sidecar.
  --install-dir <dir>             Where phux, phux-mcp and the phux-rune launcher go
                                  (default: $PHUX_INSTALL_DIR, or ~/.local/bin).
  --no-modify-path                Leave the shell profile alone (also $PHUX_NO_MODIFY_PATH=1).
  --no-repo                       On Debian, Ubuntu, Fedora and RHEL, install the release
                                  archive instead of adding phux's apt or dnf repository
                                  (also $PHUX_NO_REPO=1). The repository is the default for
                                  the stable channel, so phux updates with the system.
  --service, --no-service         On Linux, run (or skip) `phux service install` without
                                  asking: a systemd user unit plus linger, so sessions
                                  survive logout and reboot. Default: ask on a terminal,
                                  install otherwise (also $PHUX_NO_SERVICE=1).
  --rune                          Install Phux Rune from its own feed; takes no channel or pin.
  --desktop                       The same as --rune (the GPUI desktop is retired).
  --applications-dir <dir>        Desktop destination (default: /Applications if writable,
                                  else ~/Applications on macOS; $XDG_DATA_HOME or
                                  ~/.local/share on Linux; also $PHUX_DESKTOP_APPLICATIONS_DIR).
  --os <darwin|linux>, --arch <arm64|x86_64>
                                  Override platform detection.
  --dry-run                       Print what would be downloaded and where it would go.
  --verbose                       Also say what was installed where, and how it was checked.
  --help                          Show this help.

With minisign on PATH, the release checksum's signature, and the channel
manifest's (required on lts), are verified against the phux release keys. Set PHUX_REQUIRE_SIGNATURE=1 to refuse to install
without that check (0, the default, falls back to the SHA-256 alone).
EOF
}

# PATH for reading: ~ for HOME. Not for a command line; shell_quote is.
pretty_path() {
  # shellcheck disable=SC2088 # a ~ to read, never expanded
  case "${HOME:-}:$1" in
    ?*:"${HOME:-}"/*) printf '~/%s' "${1#"$HOME"/}" ;;
    *) printf '%s' "$1" ;;
  esac
}

# POSIX stand-in for `printf %q`: bare when no shell treats a character
# specially, otherwise single-quoted.
shell_quote() {
  case "$1" in
    '' | *[!A-Za-z0-9_./:@%+=-]*) printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")" ;;
    *) printf '%s' "$1" ;;
  esac
}

# Whether all of VALUE, one line, matches the extended regex PATTERN.
matches() {
  case "$1" in *'
'*) return 1 ;; esac
  printf '%s\n' "$1" | LC_ALL=C grep -Eq "^($2)\$"
}
SEMVER='(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)'

# --- downloads and digests ---------------------------------------------------

# GitHub's releases/download sometimes answers one asset with a 5xx for hours
# while its API still serves the same bytes, so a release file that fails is
# fetched once more through the API. Digests and signatures are checked as
# before, so the second source adds no trust.
API_RELEASES=https://api.github.com/repos/no-phux/phux/releases

# Fetch URL into FILE, sending the header ACCEPT when given. A stalled
# transfer (under 1 KiB/s for a minute) aborts instead of hanging.
fetch_to() {
  if command -v curl >/dev/null 2>&1; then
    if [ -n "${3:-}" ]; then
      curl -fsSL --proto =https --connect-timeout 10 --speed-limit 1024 --speed-time 60 --retry 2 \
        -H "$3" "$1" -o "$2"
    else
      curl -fsSL --proto =https --connect-timeout 10 --speed-limit 1024 --speed-time 60 --retry 2 \
        "$1" -o "$2"
    fi
  elif command -v wget >/dev/null 2>&1; then
    if [ -n "${3:-}" ]; then
      wget -q --timeout=60 --tries=2 --header="$3" -O "$2" "$1"
    else
      wget -q --timeout=60 --tries=2 -O "$2" "$1"
    fi
  else
    die "curl or wget is required to download a release"
  fi
}

download() {
  fetch_to "$1" "$2" || download_from_api "$1" "$2"
}

# The API's copy of the release asset at URL, into FILE.
download_from_api() {
  phux_message info "GitHub did not serve ${1##*/}; fetching it through the GitHub API"
  api_url="$(api_asset_url "$1" "${2}.release")" || return 1
  fetch_to "$api_url" "$2" 'Accept: application/octet-stream'
}

# Print the API URL that downloads the release asset at URL, looking its
# release up into the scratch file LOOKUP. Only a numeric asset of this
# repository's releases qualifies.
api_asset_url() {
  api_path="${1#"${RELEASES}/"}"
  [ "$api_path" != "$1" ] || return 1
  api_tag="${api_path%%/*}"
  api_name="${api_path#*/}"
  matches "$api_tag" '[A-Za-z0-9][A-Za-z0-9._+-]*' || return 1
  matches "$api_name" '[A-Za-z0-9][A-Za-z0-9._+-]*' || return 1
  fetch_to "${API_RELEASES}/tags/${api_tag}" "$2" 'Accept: application/vnd.github+json' || return 1
  tr ',{}[]' '\n\n\n\n\n' < "$2" | LC_ALL=C awk -v name="$api_name" -v prefix="${API_RELEASES}/assets/" '
    { sub(/^[ \t]+/, ""); sub(/[ \t]+$/, "") }
    index($0, "\"url\":") == 1 { url = $0; sub(/^"url": *"/, "", url); sub(/"$/, "", url); next }
    index($0, "\"name\":") == 1 {
      asset = $0; sub(/^"name": *"/, "", asset); sub(/"$/, "", asset)
      if (asset == name && index(url, prefix) == 1 && substr(url, length(prefix) + 1) ~ /^[0-9]+$/) {
        print url; found = 1; exit
      }
    }
    END { exit !found }
  '
}

sha256_of() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{ print $1 }'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{ print $1 }'
  else
    die "sha256sum or shasum is required to verify a release"
  fi
}

# The trust gate: nothing is unpacked unless FILE hashes to EXPECTED.
verify_sha256() {
  actual="$(sha256_of "$1")"
  [ "$actual" = "$2" ] \
    || die "checksum mismatch for $(basename "$1"): expected $2, downloaded $actual; nothing was installed"
}

# The digest a sha256sum-format SIDECAR publishes for NAME, and only NAME.
sidecar_digest() {
  digest="$(awk -v name="$2" '{ sub(/^\*/, "", $2) } $2 == name { print $1; exit }' "$1")"
  matches "$digest" '[0-9a-f]{64}' || die "$(basename "$1") does not cover $2"
  printf '%s\n' "$digest"
}

# --- the channel manifest ----------------------------------------------------

# Flatten the rendered manifest (two-space indent, one member per line, no
# arrays, restricted strings) into `dotted.path=value` lines. Anything else
# fails closed.
manifest_flat() {
  LC_ALL=C awk '
    function fail(why) { print "release manifest line " NR ": " why > "/dev/stderr"; bad = 1; exit 1 }
    closed { fail("content after the document") }
    NR == 1 { if ($0 != "{") fail("expected an object"); next }
    /^ *"[A-Za-z0-9_-]+": \{$/ {
      match($0, /"[^"]+"/); path[++depth] = substr($0, RSTART + 1, RLENGTH - 2); next
    }
    /^ *"[A-Za-z0-9_-]+": ("[A-Za-z0-9._:\/+-]*"|[0-9]+),?$/ {
      line = $0; sub(/^ */, "", line); sub(/,$/, "", line)
      at = index(line, "\": "); value = substr(line, at + 3); gsub(/"/, "", value)
      prefix = ""; for (i = 1; i <= depth; i++) prefix = prefix path[i] "."
      print prefix substr(line, 2, at - 2) "=" value; next
    }
    /^ *\},?$/ { if (depth == 0) closed = 1; else depth--; next }
    { fail("unrecognized line") }
    END { if (!bad && !closed) { print "release manifest is truncated" > "/dev/stderr"; exit 1 } }
  ' "$1"
}

manifest_value() {
  awk -v key="$2" 'index($0, key "=") == 1 { print substr($0, length(key) + 2); exit }' "$1"
}

# Fetch channels/NAME.json and flatten it into FLAT.
fetch_manifest() {
  url="${RELEASES}/channels/$1.json"
  raw="${2}.json"
  if command -v curl >/dev/null 2>&1; then
    { curl -fsSL --proto =https --connect-timeout 10 --max-time 30 --max-filesize 1048576 --retry 2 \
      "$url" -o "$raw" || download_from_api "$url" "$raw"; } \
      || die "could not download the $1 release manifest ($url); retry, or pin a release"
  else
    download "$url" "$raw" || die "could not download the $1 release manifest ($url)"
  fi
  [ "$(wc -c < "$raw")" -le 1048576 ] || die "the $1 release manifest exceeds 1 MiB"
  manifest_flat "$raw" > "$2" || die "the $1 release manifest is malformed"
}

# Fetch, flatten and check CHANNEL's manifest into FLAT, once per run.
load_manifest() {
  [ ! -s "$2" ] || return 0
  fetch_manifest "$1" "$2"
  [ "$(manifest_value "$2" schema_version)" = 1 ] \
    || die "the $1 release manifest has an unsupported schema; update this installer"
  [ "$(manifest_value "$2" channel)" = "$1" ] || die "the $1 release manifest names another channel"
  verify_manifest_signature "$1" "${2}.json"
}

# With minisign on PATH, CHANNEL's manifest RAW must carry a release-key
# signature (channels/CHANNEL.json.minisig). lts refuses without one; stable
# and next only warn, since their older manifests were published unsigned.
# Without minisign, verify_signature applies PHUX_REQUIRE_SIGNATURE later.
verify_manifest_signature() {
  command -v minisign >/dev/null 2>&1 || return 0
  if download "${RELEASES}/channels/$1.json.minisig" "${2}.minisig" 2>/dev/null \
    && signed_by_release_key "$2" "${2}.minisig"; then
    return 0
  fi
  [ "$1" != lts ] || die "the lts release manifest is not signed by a phux release key; nothing was installed"
  phux_message warn "the $1 release manifest is not signed by a phux release key; relying on the signed checksum"
}

# Set build_id (version on stable, commit on next) and build_sha256 for
# PRODUCT on TARGET: from PIN and PIN_SHA256 when pinned, otherwise from the
# manifest, whose digest is then the one expected.
resolve() {
  if [ -n "$3" ]; then
    build_id="$3"
    build_sha256="$4"
    return
  fi
  load_manifest "$channel" "${work}/manifest"
  key="products.$1"
  version_found="$(manifest_value "${work}/manifest" "${key}.version")"
  [ -n "$version_found" ] || die "no $1 release is published on the $channel channel yet"
  matches "$version_found" "$SEMVER" || die "the manifest names an invalid $1 version"
  sha_found="$(manifest_value "${work}/manifest" "${key}.sha")"
  matches "$sha_found" '[0-9a-f]{40}' || die "the manifest names an invalid $1 commit"
  build_sha256="$(manifest_value "${work}/manifest" "${key}.artifacts.$2.sha256")"
  matches "$build_sha256" '[0-9a-f]{64}' || die "the manifest publishes no $1 digest for $2"
  if [ "$channel" = next ]; then build_id="$sha_found"; else build_id="$version_found"; fi
}

# The one naming rule (ADR-0176 decision 1). Sets asset_stem, asset_name,
# asset_url and sidecar_url for PRODUCT's build_id on TARGET.
name_asset() {
  case "$1/$channel" in
    phux/stable | phux/lts) release="v${build_id}" asset_stem="phux-v${build_id}-$2" ext=tar.gz ;;
    phux/next) release=next asset_stem="phux-next.${build_id}-$2" ext=tar.gz ;;
  esac
  asset_name="${asset_stem}.${ext}"
  asset_url="${RELEASES}/${release}/${asset_name}"
  sidecar_url="${asset_url}.sha256"
}

# Whether a release key signed SIDECAR with SIGNATURE. -H accepts only the
# prehashed signatures CI makes, the same rule phux update enforces.
signed_by_release_key() {
  for key in $RELEASE_KEYS; do
    minisign -V -H -q -P "$key" -m "$1" -x "$2" >/dev/null 2>&1 && return 0
  done
  return 1
}

# With minisign on PATH, the asset's signed sidecar is the trust root: it
# must verify against RELEASE_KEYS and agree with the expected digest, or
# supply it. Without minisign the SHA-256 alone is checked, unless
# PHUX_REQUIRE_SIGNATURE=1 makes that a refusal (ADR-0178 decision 5).
verify_signature() {
  case "${PHUX_REQUIRE_SIGNATURE:-0}" in
    0 | 1) ;;
    *) die "PHUX_REQUIRE_SIGNATURE must be 1 (require a signature) or 0; nothing was installed" ;;
  esac
  if ! command -v minisign >/dev/null 2>&1; then
    [ "${PHUX_REQUIRE_SIGNATURE:-0}" = 0 ] \
      || die "PHUX_REQUIRE_SIGNATURE=1 but minisign is not on PATH; nothing was installed"
    detail info "minisign not found; checking the SHA-256 without its release signature"
    return 0
  fi
  download "${asset_url}.sha256" "${work}/signed.sha256" \
    || die "could not download the checksum for ${asset_name}; nothing was installed"
  download "${asset_url}.sha256.minisig" "${work}/signed.sha256.minisig" \
    || die "could not download the signature for ${asset_name}; an unsigned release is never installed"
  signed_by_release_key "${work}/signed.sha256" "${work}/signed.sha256.minisig" \
    || die "the checksum for ${asset_name} is not signed by a phux release key; nothing was installed"
  signed="$(sidecar_digest "${work}/signed.sha256" "$asset_name")"
  if [ -z "$build_sha256" ]; then
    build_sha256="$signed"
  elif [ "$signed" != "$build_sha256" ]; then
    die "the signed checksum for ${asset_name} is ${signed}, not ${build_sha256}; nothing was installed"
  fi
}

# Download PRODUCT's asset for TARGET into the work directory and verify it.
fetch_verified() {
  download "$asset_url" "${work}/${asset_name}" \
    || die "could not download ${asset_name}; nothing was installed"
  verify_signature
  if [ -z "$build_sha256" ]; then
    download "$sidecar_url" "${work}/sidecar" \
      || die "could not download the checksum for ${asset_name}; nothing was installed"
    build_sha256="$(sidecar_digest "${work}/sidecar" "$asset_name")"
  fi
  verify_sha256 "${work}/${asset_name}" "$build_sha256"
}

print_plan() {
  printf 'product: %s\nchannel: %s\nurl: %s\n' "$1" "$channel" "$asset_url"
  if [ -n "$build_sha256" ]; then echo "sha256: ${build_sha256}"; else echo "sidecar: ${sidecar_url}"; fi
  echo "destination: $2"
}

trap_signals() {
  trap 'exit 129' HUP
  trap 'exit 130' INT
  trap 'exit 143' TERM
}

# --- Linux package repositories ----------------------------------------------

# On Debian, Ubuntu, Fedora and RHEL the stable CLI comes from phux's signed
# apt or dnf repository, so it updates with the system. The signing key is
# repo_key, embedded by scripts/generate-install.sh from packaging/phux.asc:
# it is as trusted as this script, and nothing else is fetched to trust it.
# Packages stay on their releases; the signed metadata is the `repodata`
# release (docs/runbooks/linux-packages.md).
REPO_URL="${PHUX_REPO_URL:-https://github.com/no-phux/phux/releases/download}"

# apt or dnf when this host is one phux's repositories serve, and the
# installer can act as root: as root, or through sudo that needs no password
# or has a terminal to ask on.
repo_manager() {
  [ "$(uname -s)" = Linux ] && [ -r "${PHUX_OS_RELEASE:-/etc/os-release}" ] || return 1
  # shellcheck disable=SC1090,SC1091
  ids="$(. "${PHUX_OS_RELEASE:-/etc/os-release}" && printf ' %s %s ' "${ID:-}" "${ID_LIKE:-}")"
  case "$ids" in
    *' debian '* | *' ubuntu '*) manager=apt tool=apt-get ;;
    *' fedora '* | *' rhel '* | *' centos '*) manager=dnf tool=dnf ;;
    *) return 1 ;;
  esac
  command -v "$tool" >/dev/null 2>&1 || return 1
  if [ "$(id -u)" != 0 ]; then
    command -v sudo >/dev/null 2>&1 || return 1
    sudo -n true 2>/dev/null || { : </dev/tty; } 2>/dev/null || return 1
  fi
  printf '%s\n' "$manager"
}

# Under curl | sh, stdin is the rest of this script: nothing may read it.
# sudo asks for a password on the terminal, not stdin.
as_root() {
  if [ "$(id -u)" = 0 ]; then "$@" </dev/null; else sudo "$@" </dev/null; fi
}

# Add the repository for MANAGER and install phux from it. Every step is
# chained: a caller's `if` turns off set -e.
install_repo() {
  phux_message info "adding the phux $1 repository, so phux updates with the system (opt out: --no-repo)"
  repo_key > "${work}/phux.asc" || return 1
  case "$1" in
    apt)
      printf 'deb [signed-by=/etc/apt/keyrings/phux.asc] %s repodata/\n' "$REPO_URL" > "${work}/phux.list" \
        && as_root install -d -m 755 /etc/apt/keyrings \
        && as_root install -m 644 "${work}/phux.asc" /etc/apt/keyrings/phux.asc \
        && as_root install -m 644 "${work}/phux.list" /etc/apt/sources.list.d/phux.list \
        && as_root apt-get update -qq -o Dir::Etc::sourcelist=sources.list.d/phux.list \
          -o Dir::Etc::sourceparts=- -o APT::Get::List-Cleanup=0 \
        && as_root env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq phux
      ;;
    dnf)
      printf '[phux]\nname=phux\nbaseurl=%s\nenabled=1\ngpgcheck=1\nrepo_gpgcheck=1\nmetadata_expire=1h\ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-phux\n' \
        "$REPO_URL" > "${work}/phux.repo" \
        && as_root install -D -m 644 "${work}/phux.asc" /etc/pki/rpm-gpg/RPM-GPG-KEY-phux \
        && as_root install -m 644 "${work}/phux.repo" /etc/yum.repos.d/phux.repo \
        && as_root rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-phux \
        && as_root dnf install -y -q phux
      ;;
  esac
}
repo_key() {
  cat <<'KEY'
-----BEGIN PGP PUBLIC KEY BLOCK-----

mQINBGr4zb8BEAClpZpRRTXio8eVaYzm8SOwJ4EaGUC8eS2RtN4ipM2bEmGr0+Nc
ztWmyfhigSKtcnpPm711Df1C3B7cgGnFFTp0HvxsUBVx3ynyZkLP76vrhCQPGWwf
kQEV1EZkSRAl87/TRsy8GIEAcxRnYd87yx1DxUaBn4rm1yGe6YSiZJEpmAtd1A6n
V5QLlPGWYx2zs26FMEtjfkyo7c3LP9W6Z+mMNeQxehtRwawpeWu5egFRsSTFSJU8
F2D45taksnXDtHdBUsjNMRGn1PzBxuXIIcRlpHNjZa3WB4vNuvJ5udtFYf+HhU+O
dd3KreLB1RaQYODjC3I1W2t/lyiRRK++WbkWprnNcyFPO2lEEMCkmeaForomKoZJ
5sZ/+p1NMJDyh7dQvw5QhCxVZtx7QBN0U8TYP6iWJTt7/AwIHIDjwQ5OFIcbQ/Sz
IxblFZmUQGckU1NTfEHU5vs6AuL2QuX3z2sGOfowx74eLH/Ab70RsM0sDWg/9g2Y
EOA5AU0ad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vy7WqXksMRlftIPHwoto2/Mik9Ewjx/su3zIwO+ePBUf6ezq
N8SgUGX8cUBGMJWmaL5V5cZA01Vgh631mzUVU2fZpK/19jv5gEVLqSuCW04ksznW
SdTrwIj26qgQCmxRNwFnZ62aaQ0WbwhDt0FjbKqowgH3meclyw==
=2OAY
-----END PGP PUBLIC KEY BLOCK-----
KEY
}

# --- the CLI -----------------------------------------------------------------

LICENSES='README.md LICENSE NOTICE THIRD-PARTY-NOTICES.md LICENSE-MIT LICENSE-APACHE'

# A tarball member under STEM: the directory, a binary, or a license file
# (both the current and the pre-0.36 layout).
cli_member() {
  [ "$2" = "$1" ] || [ "$2" = "$1/" ] && return 0
  for allowed in phux phux-mcp $LICENSES; do
    [ "$2" != "$1/$allowed" ] || return 0
  done
  return 1
}

# GNU stat reads -f as "file system", so try its -c first.
link_count() {
  if stat -c '%h' "$1" >/dev/null 2>&1; then stat -c '%h' "$1"; else stat -f '%l' "$1"; fi
}

# Unpack the verified tarball into the work directory; refuse any member a
# release does not contain, and any link.
unpack_cli() {
  tar -tzf "${work}/${asset_name}" > "${work}/members"
  [ -s "${work}/members" ] || die "the archive is empty"
  while IFS= read -r member; do
    cli_member "$asset_stem" "$member" || die "unexpected archive member: $member"
  done < "${work}/members"
  mkdir "${work}/cli"
  tar -xzf "${work}/${asset_name}" -C "${work}/cli"
  find "${work}/cli" -mindepth 1 -print | while IFS= read -r path; do
    rel="${path#"${work}/cli"/}"
    cli_member "$asset_stem" "$rel" || die "unexpected extracted member: $rel"
    [ ! -L "$path" ] || die "archive member must not be a symlink: $rel"
    [ -d "$path" ] || { [ -f "$path" ] && [ "$(link_count "$path")" = 1 ]; } \
      || die "archive member must be a regular file: $rel"
  done
  for binary in phux phux-mcp; do
    [ -f "${work}/cli/${asset_stem}/${binary}" ] || die "the archive has no ${binary}"
  done
}

# Publish phux and phux-mcp into install_dir by rename, restoring the
# previous pair if anything is interrupted.
publish_cli() {
  mkdir -p "$install_dir"
  cli_lock="${install_dir}/.phux-install.lock"
  trap '' HUP INT TERM
  mkdir "$cli_lock" 2>/dev/null \
    || die "another phux install is publishing to ${install_dir}; if none is running, remove ${cli_lock}"
  cli_locked=1
  trap_signals
  cli_publish="$(mktemp -d "${install_dir}/.phux-install.XXXXXX")"
  mkdir "${cli_publish}/backup"
  for binary in phux phux-mcp; do
    target_path="${install_dir}/${binary}"
    if [ -e "$target_path" ] && [ ! -f "$target_path" ] && [ ! -L "$target_path" ]; then
      die "refusing to replace non-file install destination: ${target_path}"
    fi
    cp "${work}/cli/${asset_stem}/${binary}" "${cli_publish}/${binary}"
    chmod 755 "${cli_publish}/${binary}"
  done
  cli_publishing=1
  for binary in phux phux-mcp; do
    if [ -e "${install_dir}/${binary}" ] || [ -L "${install_dir}/${binary}" ]; then
      mv "${install_dir}/${binary}" "${cli_publish}/backup/${binary}"
    fi
  done
  for binary in phux phux-mcp; do
    # Recorded before the rename, so a signal right after it still rolls back.
    cli_published="$cli_published $binary"
    mv "${cli_publish}/${binary}" "${install_dir}/${binary}"
  done
  cli_publishing=0
  printf '%s\n' "$channel" > "${install_dir}/.phux-channel"
}

rollback_cli() {
  [ "$cli_publishing" -eq 1 ] || return 0
  for binary in $cli_published; do rm -f "${install_dir}/${binary}"; done
  for binary in phux phux-mcp; do
    if [ -e "${cli_publish}/backup/${binary}" ] || [ -L "${cli_publish}/backup/${binary}" ]; then
      mv -f "${cli_publish}/backup/${binary}" "${install_dir}/${binary}"
    fi
  done
}

# Append one idempotent PATH line to the profile the user's shell reads, and
# print it. Never fatal: the printed remedy covers a profile it cannot write.
add_to_profile() {
  [ -n "${HOME:-}" ] || return 1
  quoted="$(shell_quote "$1")"
  line="export PATH=${quoted}:\"\$PATH\""
  case "$(basename "${SHELL:-sh}")" in
    fish) profile="${XDG_CONFIG_HOME:-$HOME/.config}/fish/conf.d/phux.fish" line="fish_add_path -g ${quoted}" ;;
    zsh) profile="${ZDOTDIR:-$HOME}/.zshrc" ;;
    # macOS terminals start login shells, which read .bash_profile.
    bash) if [ "$(uname -s)" = Darwin ]; then profile="$HOME/.bash_profile"; else profile="$HOME/.bashrc"; fi ;;
    *) profile="$HOME/.profile" ;;
  esac
  if ! grep -Fqx "$line" "$profile" 2>/dev/null; then
    mkdir -p "$(dirname "$profile")" 2>/dev/null || return 1
    printf '\n# Added by the phux installer\n%s\n' "$line" >> "$profile" 2>/dev/null || return 1
  fi
  printf '%s\n' "$profile"
}

# The installer's last words: that phux is in, and the one thing to do next.
report_path() {
  dir="$(cd "$install_dir" && pwd -P)"
  found="$(command -v phux 2>/dev/null || true)"
  if [ "${found#/}" != "$found" ] && [ "$(cd "$(dirname "$found")" && pwd -P)/phux" = "${dir}/phux" ]; then
    # shellcheck disable=SC2016 # backticks mark the command, not a substitution
    echo 'phux is installed. Run `phux` to start.'
    return
  fi
  on_path=0
  old_ifs="$IFS"
  IFS=:
  set -f
  for entry in $PATH; do
    [ "$(cd "$entry" 2>/dev/null && pwd -P)" != "$dir" ] || on_path=1
  done
  set +f
  IFS="$old_ifs"
  # shellcheck disable=SC2016 # backticks mark a command; the PATH line expands when it runs
  if [ "$on_path" -eq 1 ]; then
    printf 'phux is installed in %s, but %s comes first on PATH. Run %s, or move %s first on PATH.\n' \
      "$(pretty_path "$dir")" "$found" "$(shell_quote "${dir}/phux")" "$(pretty_path "$dir")"
  elif [ "$modify_path" -eq 1 ] && profile="$(add_to_profile "$dir")"; then
    printf 'phux is installed. Open a new terminal and run `phux` (%s now adds it to PATH).\n' "$(pretty_path "$profile")"
  else
    printf 'phux is installed in %s. Add it to PATH with export PATH=%s:"$PATH", then run `phux`.\n' \
      "$(pretty_path "$dir")" "$(shell_quote "$dir")"
  fi
}

# On Linux a plain server is not restarted after a reboot and often ends at
# logout. `phux service install --adopt` runs it as a systemd user unit and
# turns on linger; --adopt never stops a running server, and is a no-op when
# the unit already runs it. Without a terminal to ask on, install: a new
# customer's sessions should survive a reboot without a second command.
offer_service() {
  [ "$service" != 0 ] && [ "$(uname -s)" = Linux ] || return 0
  phux="${install_dir}/phux"
  [ -x "$phux" ] || phux="$(command -v phux 2>/dev/null)" || return 0
  if ! systemctl --user show-environment >/dev/null 2>&1; then
    [ "$service" = ask ] || phux_message warn "no systemd user manager here; the server runs unsupervised"
    return 0
  fi
  if [ "$service" = ask ] && [ -t 2 ] && { : </dev/tty; } 2>/dev/null; then
    printf 'Keep phux sessions running after logout and reboot? (systemd user service) [Y/n] ' >&2
    read -r answer </dev/tty || answer=""
    case "$answer" in
      [Nn]*)
        echo "later: $(shell_quote "$phux") service install --adopt"
        return 0
        ;;
    esac
  fi
  "$phux" service install --adopt \
    || phux_message warn "the server is not supervised; retry with: $(shell_quote "$phux") service install --adopt"
}

# PIN and PIN_SHA256 pin the CLI; empty follows the channel.
install_cli() {
  if [ "$repo" -eq 1 ] && [ "$channel" = stable ] && [ -z "$1" ] && manager="$(repo_manager)"; then
    if [ "$dry_run" -eq 1 ]; then
      printf 'product: phux\nchannel: stable\nrepository: %s %s\ndestination: /usr/bin\n' "$manager" "$REPO_URL"
      return
    fi
    if install_repo "$manager"; then
      [ "$rune" -eq 1 ] || install_dir=/usr/bin
      detail ok "installed phux from the phux $manager repository; $manager keeps it updated"
      return
    fi
    phux_message warn "the $manager repository did not install phux; installing the release archive instead"
  fi
  resolve phux "$target" "$1" "$2"
  name_asset phux "$target"
  if [ "$dry_run" -eq 1 ]; then
    print_plan phux "$install_dir"
    return
  fi
  fetch_verified
  unpack_cli
  publish_cli
  detail ok "installed phux ${build_id} for ${target} to ${install_dir}"
  if [ "$target" = aarch64-apple-darwin ] && [ "$channel" != next ]; then
    # Best effort, in a subshell so a failure cannot undo the CLI install.
    (install_server_app) || phux_message warn "phux Server.app was not installed; the server runs from ${install_dir}/phux"
  fi
}

# --- phux Server.app (macOS) -------------------------------------------------

# Install the release's signed phux Server.app beside the CLI, into
# ~/Library/Application Support/sh.phux/Server/Versions/v<version>, point
# Versions/Current at it, and keep only the release Current named before.
# The server starts through Versions/Current so macOS privacy grants survive
# updates (docs/install.md#macos-permissions); phux update does the same.
install_server_app() {
  [ -n "${HOME:-}" ] || die "HOME is not set"
  release="v${build_id}"
  asset_stem="phux-server-${release}-${target}"
  asset_name="${asset_stem}.tar.gz"
  asset_url="${RELEASES}/${release}/${asset_name}"
  sidecar_url="${asset_url}.sha256"
  build_sha256=""
  fetch_verified
  tar -tzf "${work}/${asset_name}" > "${work}/server-members" || die "could not read ${asset_name}"
  while IFS= read -r member; do
    case "$member" in
      "$asset_stem" | "$asset_stem/" | "$asset_stem/phux Server.app/"*) ;;
      *) die "unexpected archive member: $member" ;;
    esac
    case "/$member/" in */../* | */./*) die "unexpected archive member: $member" ;; esac
  done < "${work}/server-members"
  server_root="$HOME/Library/Application Support/sh.phux/Server"
  mkdir -p "$server_root/Versions"
  stage="$(mktemp -d "$server_root/.incoming.XXXXXX")"
  trap 'rm -rf "$stage"' EXIT
  tar -xzf "${work}/${asset_name}" -C "$stage"
  app="$stage/$asset_stem/phux Server.app"
  [ -f "$app/Contents/MacOS/phux" ] || die "${asset_name} has no Contents/MacOS/phux"
  [ -z "$(find "$stage" -type l -print -quit)" ] || die "${asset_name} contains a symlink"
  versions="$server_root/Versions"
  # A release already present stays: a running server may be executing it.
  if [ ! -e "$versions/$release/phux Server.app" ]; then
    rm -rf "${versions:?}/$release"
    mkdir "$versions/$release"
    mv "$app" "$versions/$release/phux Server.app"
  fi
  previous="$(readlink "$versions/Current" 2>/dev/null || true)"
  # -n replaces the link itself, not an entry inside the directory it names.
  ln -sfn "$release" "$versions/Current"
  for entry in "$versions"/*; do
    case "${entry##*/}" in
      Current | "$release" | "$previous") ;;
      *) rm -rf "$entry" ;;
    esac
  done
  detail ok "installed phux Server.app ${build_id} to ${versions}/Current"
}

# --- Phux Rune ---------------------------------------------------------------

plist() {
  /usr/libexec/PlistBuddy -c "Print :$2" "$1/Contents/Info.plist" 2>/dev/null
}

macos_at_least() {
  awk -v actual="$1" -v minimum="$2" 'BEGIN {
    pattern = "^[0-9]+([.][0-9]+){0,2}$"
    if (actual !~ pattern || minimum !~ pattern) exit 1
    split(actual, a, "."); split(minimum, b, ".")
    for (i = 1; i <= 3; i++) {
      if (a[i]+0 > b[i]+0) exit 0
      if (a[i]+0 < b[i]+0) exit 1
    }
  }'
}

lock_applications() {
  mkdir -p "$applications_dir"
  exec 9>"${applications_dir}/.phux-desktop-install.lock"
  lockf -s -t 0 9 || die "another install is publishing to ${applications_dir}"
}

rollback_app() {
  [ "$app_publishing" -eq 1 ] || return 0
  [ "$app_published" -eq 0 ] || rm -rf "$installed"
  [ ! -d "${app_publish}/previous.app" ] || mv -f "${app_publish}/previous.app" "$installed" || {
    phux_message error "rollback failed; the previous app is at ${app_publish}/previous.app"
    app_publish=""
  }
}

has_cli() {
  for candidate in "${install_dir}/phux" "${HOME:-}/.local/bin/phux" "${HOME:-}/.cargo/bin/phux" /opt/homebrew/bin/phux /usr/local/bin/phux /usr/bin/phux; do
    [ ! -x "$candidate" ] || return 0
  done
  command -v phux >/dev/null 2>&1
}

linux_data_home() {
  case "${XDG_DATA_HOME:-}" in
    /*) printf '%s\n' "$XDG_DATA_HOME" ;;
    *) printf '%s\n' "${HOME:-}/.local/share" ;;
  esac
}

register_desktop_entry() {
  desktop_source="$1"
  [ -f "$desktop_source" ] || return 1
  bundle_path="$(cd "$installed" && pwd -P)" || return 1
  case "$bundle_path" in *'
'*) return 1 ;; esac
  executable="$(printf '%s' "${bundle_path}/$3" | sed 's/%/%%/g; s/[\\"`$]/\\&/g; s/\\/\\\\/g')"
  icon="$(printf '%s' "${bundle_path}/$4" | sed 's/\\/\\\\/g')"
  entries="$(linux_data_home)/applications"
  mkdir -p "$entries" || return 1
  [ ! -d "${entries}/$2.desktop" ] || return 1
  entry="$(mktemp "${entries}/.phux-desktop.XXXXXX")" || return 1
  # The executable is replaced; the field codes after it (`%u`) stay.
  if PHUX_DESKTOP_EXEC="\"${executable}\"" PHUX_DESKTOP_ICON="$icon" awk '
    /^Exec=/ { codes = $0; sub(/^Exec=[^ ]*/, "", codes); print "Exec=" ENVIRON["PHUX_DESKTOP_EXEC"] codes; next }
    /^Icon=/ { print "Icon=" ENVIRON["PHUX_DESKTOP_ICON"]; next }
    { print }
  ' "$desktop_source" > "$entry" && chmod 644 "$entry" && mv -f "$entry" "${entries}/$2.desktop"; then
    register_scheme_handler "$entries" "$2.desktop"
    return 0
  fi
  rm -f "$entry"
  return 1
}

# phux://connect links open the app: the entry's MimeType names the scheme,
# and the desktop's own tools make it the handler. Without them a desktop
# still reads the entry when it next scans; nothing here is fatal.
register_scheme_handler() {
  if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database "$1" >/dev/null 2>&1 || true
  fi
  if command -v xdg-mime >/dev/null 2>&1; then
    xdg-mime default "$2" x-scheme-handler/phux >/dev/null 2>&1 \
      || phux_message warn "could not make Phux Rune open phux:// links; run: xdg-mime default $2 x-scheme-handler/phux"
  fi
}

# Launch Services learns a bundle's schemes when it is first opened; register
# it now so a phux://connect link opens it before then.
register_bundle_macos() {
  lsregister=/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister
  [ ! -x "$lsregister" ] || "$lsregister" -f "$1" >/dev/null 2>&1 || true
}

# The update feed names one version, with a digest per target. Sets build_id,
# build_sha256 and the asset names; versions keep their -alpha.N here.
resolve_rune() {
  [ -s "${work}/rune" ] || fetch_manifest rune "${work}/rune" \
    || die "the Phux Rune feed is malformed"
  [ "$(manifest_value "${work}/rune" schema)" = 1 ] \
    || die "the Phux Rune feed has an unsupported schema; update this installer"
  build_id="$(manifest_value "${work}/rune" version)"
  matches "$build_id" "${SEMVER}(-alpha\\.(0|[1-9][0-9]*))?" || die "the feed names an invalid Phux Rune version"
  build_sha256="$(manifest_value "${work}/rune" "targets.${target}.sha256")"
  matches "$build_sha256" '[0-9a-f]{64}' || die "the feed publishes no Phux Rune digest for ${target}"
  case "$target" in
    aarch64-apple-darwin) asset_name="phux-rune-${build_id}-macos-arm64.zip" ;;
    aarch64-unknown-linux-gnu) asset_name="phux-rune-${build_id}-linux-aarch64.tar.gz" ;;
    *) asset_name="phux-rune-${build_id}-linux-x86_64.tar.gz" ;;
  esac
  asset_url="${RELEASES}/rune-v${build_id}/${asset_name}"
  sidecar_url="${asset_url}.sha256"
}

unpack_rune_macos() {
  unzip -Z1 "${work}/${asset_name}" > "${work}/members" || die "could not read the archive"
  unzip -Z -l "${work}/${asset_name}" | awk '$1 ~ /^l/ { found = 1 } END { exit found }' \
    || die "the archive contains symlinks"
  while IFS= read -r member; do
    case "$member" in
      */../* | */..) die "unsafe archive member path: $member" ;;
      "Phux Rune.app/"*) ;;
      *) die "unexpected archive member: $member" ;;
    esac
  done < "${work}/members"
  mkdir "${work}/rune-app"
  unzip -q "${work}/${asset_name}" -d "${work}/rune-app"
  app="${work}/rune-app/Phux Rune.app"
  [ -x "${app}/Contents/MacOS/phux-rune" ] || die "the archive has no Phux Rune executable"
  codesign --verify --deep --strict "$app" || die "the Phux Rune signature does not verify"
  [ "$(plist "$app" CFBundleIdentifier)" = sh.phux.rune ] || die "the archive is not Phux Rune"
  [ "$(plist "$app" CFBundleShortVersionString)" = "$build_id" ] || die "the bundle is not version ${build_id}"
  minimum_macos="$(plist "$app" LSMinimumSystemVersion)" || die "the bundle has no minimum macOS version"
  macos_at_least "$(sw_vers -productVersion)" "$minimum_macos" || die "Phux Rune requires macOS ${minimum_macos}"
}

publish_rune_macos() {
  installed="${applications_dir}/Phux Rune.app"
  if [ -e "$installed" ] && [ "$(plist "$installed" CFBundleIdentifier || true)" != sh.phux.rune ]; then
    die "refusing to replace an unrelated ${installed}"
  fi
  app_publish="$(mktemp -d "${applications_dir}/.phux-desktop-install.XXXXXX")"
  ditto "$app" "${app_publish}/Phux Rune.app"
  app_publishing=1
  if [ -e "$installed" ]; then mv "$installed" "${app_publish}/previous.app"; fi
  app_published=1
  mv "${app_publish}/Phux Rune.app" "$installed"
  app_publishing=0
  xattr -d com.apple.quarantine "$installed" 2>/dev/null || true
}

install_rune_macos() {
  for tool in unzip ditto codesign lockf; do
    command -v "$tool" >/dev/null 2>&1 || die "$tool is required to install Phux Rune"
  done
  fetch_verified
  unpack_rune_macos
  lock_applications
  publish_rune_macos
  register_bundle_macos "$installed"
  detail ok "installed Phux Rune ${build_id} to ${applications_dir}"
  rune_installed="Phux Rune is installed. Open Phux Rune from $(pretty_path "$(cd "$applications_dir" && pwd -P)")."
}

rune_member() {
  case "${1#*/}" in
    phux-rune | phux-rune.release | README.md | LICENSE | NOTICE | THIRD-PARTY-NOTICES.txt | \
    Inter-OFL.txt | JetBrainsMono-OFL.txt | PaperMono-OFL.txt | \
    tmd | tmd-LICENSE.txt | tmd-THIRD-PARTY-NOTICES.md | tmd-VERSION.txt | \
    sh.phux.rune.desktop | sh.phux.rune.png) return 0 ;;
    *) return 1 ;;
  esac
}

# Regular files under one directory, checked before anything is extracted: a
# link must never redirect a later member.
unpack_rune_linux() {
  stem="${asset_name%.tar.gz}"
  tar -tzf "${work}/${asset_name}" > "${work}/members" || die "could not read the archive"
  tar -tvzf "${work}/${asset_name}" > "${work}/types" || die "could not read archive types"
  LC_ALL=C awk 'substr($0,1,1) !~ /[-d]/ { bad=1 } END { exit bad }' "${work}/types" \
    || die "Phux Rune archive members must be regular files or directories, not links"
  while IFS= read -r member; do
    case "$member" in
      "$stem" | "$stem/") continue ;;
      "$stem"/*) rune_member "$member" && continue ;;
    esac
    die "unexpected archive member: $member"
  done < "${work}/members"
  mkdir "${work}/rune-app"
  tar -xzf "${work}/${asset_name}" -C "${work}/rune-app" --no-same-owner
  app="${work}/rune-app/${stem}"
  [ -x "${app}/phux-rune" ] || die "the archive has no Phux Rune executable"
  [ -f "${app}/phux-rune.release" ] || die "the archive is not a Phux Rune release"
  [ "$("${app}/phux-rune" --version 2>/dev/null)" = "phux-rune ${build_id}" ] \
    || die "the binary does not run here, or is not version ${build_id}; nothing was installed"
}

publish_rune_linux() {
  mkdir -p "$applications_dir"
  app_lock="${applications_dir}/.phux-desktop-install.lock"
  trap '' HUP INT TERM
  mkdir "$app_lock" 2>/dev/null || die "another install is publishing; if none is running, remove ${app_lock}"
  app_locked=1
  trap_signals
  installed="${applications_dir}/phux-rune"
  [ ! -L "$installed" ] || die "refusing to replace a symlink: ${installed}"
  if [ -e "$installed" ] && [ ! -f "${installed}/phux-rune.release" ]; then
    die "refusing to replace an unrelated ${installed}"
  fi
  app_publish="$(mktemp -d "${applications_dir}/.phux-desktop-install.XXXXXX")"
  cp -R "$app" "${app_publish}/phux-rune"
  app_publishing=1
  if [ -e "$installed" ]; then mv "$installed" "${app_publish}/previous.app"; fi
  app_published=1
  mv "${app_publish}/phux-rune" "$installed"
  app_publishing=0
}

install_rune_linux() {
  fetch_verified
  unpack_rune_linux
  publish_rune_linux
  bundle="$(cd "$installed" && pwd -P)"
  if ! { mkdir -p "$install_dir" && [ ! -d "${install_dir}/phux-rune" ] \
    && ln -sf "${bundle}/phux-rune" "${install_dir}/phux-rune"; }; then
    phux_message warn "could not install the phux-rune launcher; run ${bundle}/phux-rune"
  fi
  register_desktop_entry "${installed}/sh.phux.rune.desktop" sh.phux.rune phux-rune sh.phux.rune.png \
    || phux_message warn "could not register the menu entry; run ${bundle}/phux-rune"
  detail ok "installed Phux Rune ${build_id} to ${installed}"
  if [ -x "${install_dir}/phux-rune" ]; then run="phux-rune"; else run="$(shell_quote "${bundle}/phux-rune")"; fi
  rune_installed="Phux Rune is installed. Open Phux Rune from your apps (or run \`${run}\`)."
}

# On its own feed: there is no channel to pick and nothing to pin, and the
# app updates itself from here on.
install_rune() {
  case "$target" in
    aarch64-apple-darwin | x86_64-unknown-linux-gnu | aarch64-unknown-linux-gnu) ;;
    *) die "no Phux Rune build for ${target}" ;;
  esac
  [ "$target" != aarch64-apple-darwin ] || [ "$dry_run" -eq 1 ] || [ "$(uname -s)" = Darwin ] \
    || die "the macOS build of Phux Rune installs only on macOS"
  if ! has_cli; then
    detail info "phux CLI not found; installing it first"
    install_cli "" ""
  fi
  resolve_rune
  if [ "$dry_run" -eq 1 ]; then
    print_plan rune "$applications_dir"
    return
  fi
  if [ "$target" = aarch64-apple-darwin ]; then
    install_rune_macos
  else
    install_rune_linux
  fi
}

# --- main --------------------------------------------------------------------

channel="${PHUX_CHANNEL:-stable}"
pin=""
pinned_flag=""
pin_sha256=""
install_dir="${PHUX_INSTALL_DIR:-${HOME:-}/.local/bin}"
applications_dir="${PHUX_DESKTOP_APPLICATIONS_DIR:-}"
rune=0
dry_run=0
verbose=0
os=""
arch=""
modify_path=1
case "${PHUX_NO_MODIFY_PATH:-}" in '' | 0) ;; *) modify_path=0 ;; esac
service=ask
case "${PHUX_NO_SERVICE:-}" in '' | 0) ;; *) service=0 ;; esac
# A chosen place or platform means the archive; so does PHUX_NO_REPO.
repo=1
case "${PHUX_NO_REPO:-}" in '' | 0) ;; *) repo=0 ;; esac
[ -z "${PHUX_INSTALL_DIR:-}" ] || repo=0

while [ "$#" -gt 0 ]; do
  case "$1" in
    --channel | --version | --revision | --sha256 | --install-dir | --applications-dir | --os | --arch)
      [ "$#" -ge 2 ] && [ -n "$2" ] || die "$1 requires a value"
      ;;
  esac
  case "$1" in
    --channel) channel="$2" ;;
    --version)
      pin="${2#v}"
      pinned_flag=--version
      ;;
    --revision) pin="$2" pinned_flag=--revision ;;
    --sha256) pin_sha256="$2" ;;
    --install-dir) install_dir="$2" repo=0 ;;
    --applications-dir) applications_dir="$2" ;;
    --os) os="$2" repo=0 ;;
    --arch) arch="$2" repo=0 ;;
    --desktop)
      phux_message info "the GPUI desktop is retired; installing Phux Rune"
      rune=1
      ;;
    --rune) rune=1 ;;
    --dry-run) dry_run=1 ;;
    --verbose) verbose=1 ;;
    --no-modify-path) modify_path=0 ;;
    --no-repo) repo=0 ;;
    --service) service=1 ;;
    --no-service) service=0 ;;
    --help | -h) usage; exit 0 ;;
    *) die "unknown option: $1" ;;
  esac
  case "$1" in --desktop | --rune | --dry-run | --verbose | --no-modify-path | --no-repo | --service | --no-service) shift ;; *) shift 2 ;; esac
done

if [ "$rune" -eq 1 ]; then
  [ "$channel" != next ] && [ -z "$pin" ] \
    || die "--channel next and pins do not combine with --rune"
fi
case "$channel" in
  latest) channel=stable ;;
  stable | next | lts) ;;
  *) die "--channel must be stable, latest, next, or lts" ;;
esac
if [ -n "$pin" ]; then
  if [ "$channel" = next ]; then
    [ "$pinned_flag" = --revision ] && matches "$pin" '[0-9a-f]{40}' \
      || die "on the next channel, pin a build with --revision <40-character commit>"
  else
    [ "$pinned_flag" = --version ] && matches "$pin" "$SEMVER" \
      || die "on the $channel channel, pin a release with --version X.Y.Z"
  fi
fi
[ -z "$pin_sha256" ] || { [ -n "$pin" ] && matches "$pin_sha256" '[0-9a-f]{64}'; } \
  || die "--sha256 needs 64 lowercase hex digits and a --version or --revision pin"
[ -n "$install_dir" ] || die "--install-dir resolved to an empty path"
if [ -z "$applications_dir" ]; then
  case "${os:-$(uname -s)}" in
    [Ll]inux) applications_dir="$(linux_data_home)" ;;
    *) if [ -w /Applications ]; then applications_dir=/Applications; else applications_dir="${HOME:-}/Applications"; fi ;;
  esac
fi

case "${os:-$(uname -s)}/${arch:-$(uname -m)}" in
  [Dd]arwin/arm64 | [Dd]arwin/aarch64) target=aarch64-apple-darwin ;;
  [Ll]inux/x86_64 | [Ll]inux/amd64) target=x86_64-unknown-linux-gnu ;;
  [Ll]inux/arm64 | [Ll]inux/aarch64) target=aarch64-unknown-linux-gnu ;;
  *) die "no phux release for ${os:-$(uname -s)}/${arch:-$(uname -m)}; build from source" ;;
esac

work="$(mktemp -d)"
cli_locked=0
cli_publishing=0
cli_published=""
cli_publish=""
app_publishing=0
app_published=0
app_publish=""
app_locked=0
app_lock=""
cleanup() {
  rollback_cli
  rollback_app || true
  rm -rf "$work" "$cli_publish" "$app_publish"
  [ "$cli_locked" -eq 0 ] || rmdir "${install_dir}/.phux-install.lock" 2>/dev/null || true
  [ "$app_locked" -eq 0 ] || rmdir "$app_lock" 2>/dev/null || true
}
trap cleanup EXIT
trap_signals

rune_installed=""
if [ "$rune" -eq 1 ]; then
  install_rune
else
  install_cli "$pin" "$pin_sha256"
fi
[ "$dry_run" -eq 1 ] || offer_service
if [ "$dry_run" -eq 1 ]; then
  :
elif [ -n "$rune_installed" ]; then
  printf '%s\n' "$rune_installed"
else
  report_path
fi
