#!/bin/sh
# The RemoteHost CLI installer: what
#
#   curl -fsSL https://remotehost.ai/install | sh
#
# runs, and what `remote update` runs again (REM-6888). It downloads the
# `remote` program for this machine and puts it in ~/.remotehost/bin, with
# remote-network-helper beside it when the release has one (below). It
# needs no Node.js, npm, jq or python: curl or wget, tar, and a sha512 tool
# are all it uses. src/pages/install.ts serves this file byte for byte.
#
#   REMOTEHOST_VERSION      a version (2.0.0) or a dist-tag (beta); default latest
#   REMOTEHOST_INSTALL_DIR  where remote and rh go; default ~/.remotehost/bin
#
# Where the program comes from. `remote` is a Rust program published to npm
# as four platform packages, @remotehost/cli-<darwin|linux>-<arm64|x64>, each
# one tarball that holds package/bin/remote (clients/remote/npm). This script
# reads that package's metadata from the npm registry, downloads its tarball,
# checks the tarball's sha512 against the metadata before unpacking it, and
# installs the program.
#
# The signature (REM-6999). Each Linux tarball of a release is signed with
# RemoteHost's CLI release key, a Cloud KMS key, with cosign; the Sigstore
# bundle is in the same release's @remotehost/cli package, at
# package/signatures/<platform>.sigstore.json. On Linux, when cosign is on
# PATH and runs, the script downloads that package too (its sha512 checked
# against its own metadata, as above) and has cosign check the tarball's
# signature against COSIGN_PUBLIC_KEY, below, before anything is unpacked:
# a release with no signature, or one that does not verify, is not
# installed. Without cosign it checks the sha512 alone, as it always has;
# macOS's builds carry Apple's signature and notarization instead. COSIGN_PUBLIC_KEY is
# clients/remote/release/cosign.pub's key (a test holds it to that),
# pinned once 2.0.2, the first signed release, was out (REM-7008). A
# release from before 2.0.2 carries no signature, so a Linux machine with
# cosign is refused it.
#
# The network helper (REM-6930). `remote network join --mode rootless` runs
# remote-network-helper, which it looks for in its own directory and nowhere
# else. A release that has it holds package/bin/remote-network-helper in the
# same tarball, so it is covered by the same checksum, and it is installed
# beside remote. A release from before that holds none: remote is installed
# alone, and a helper an earlier install left is removed, since it is not
# that release's.
#
# Which version. The version or dist-tag is resolved on the PLATFORM package,
# never on @remotehost/cli: GET <registry>/@remotehost/cli-<platform>/<tag>.
# A platform package exists only for releases that have a binary, so its
# `latest` is always a version this script can install, where
# @remotehost/cli's `latest` can still be 1.0.1, the last Node.js release,
# which has none. A version with no binary (1.0.1, or one never published)
# answers 404 there, and the script says so and names the npm command. It
# never runs npm itself.
#
# It edits no shell startup file: when the install directory is not on PATH
# it prints the line to add. It never asks a question and never reads stdin,
# which is where the script itself arrives when piped. Everything is in
# functions and the last line starts it, so a download cut short runs nothing.

set -eu

REGISTRY="${REMOTEHOST_INSTALL_TEST_REGISTRY:-https://registry.npmjs.org}"
CLI_PACKAGE="@remotehost/cli"
SUPPORTED="macOS (arm64, x64) and Linux (x64, arm64)"
ISSUES="https://github.com/remotehostai/cli/issues"

# The CLI release key's public half (the header's "The signature"),
# clients/remote/release/cosign.pub's key. Pinned once 2.0.2, the first
# signed release, was out (REM-7008).
COSIGN_PUBLIC_KEY='-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8F2wIcovrBOZlIx1wT/m/S4QZdNO
n+fp11U/nGtINpZEuWrUsLQQVubBe/A9/M9iFLf5c7V95ybuL02NTNQwGg==
-----END PUBLIC KEY-----'

tmp=""
HELPER="remote-network-helper"

staged=""
staged_helper=""
staged_link=""
http_status=""
http_error=""

# ---------------------------------------------------------------------------
# Output

bold=""
dim=""
green=""
red=""
reset=""

# Colour only for a terminal that wants it (https://no-color.org).
setup_colors() {
  [ -z "${NO_COLOR:-}" ] || return 0
  [ "${TERM:-dumb}" != dumb ] || return 0
  [ -t 1 ] && [ -t 2 ] || return 0
  bold=$(printf '\033[1m')
  dim=$(printf '\033[2m')
  green=$(printf '\033[32m')
  red=$(printf '\033[31m')
  reset=$(printf '\033[0m')
}

say() {
  printf '%s\n' "$*"
}

step() {
  printf '  %s%s%s\n' "$dim" "$*" "$reset"
}

# fail <what happened> [<what to do next>...]
fail() {
  printf '\n%serror%s: %s\n' "$red" "$reset" "$1" >&2
  shift
  for line in "$@"; do
    printf '  %s\n' "$line" >&2
  done
  exit 1
}

cleanup() {
  [ -z "$staged" ] || rm -f "$staged"
  [ -z "$staged_helper" ] || rm -f "$staged_helper"
  [ -z "$staged_link" ] || rm -f "$staged_link"
  [ -z "$tmp" ] || rm -rf "$tmp"
}

has() {
  command -v "$1" >/dev/null 2>&1
}

# A path as a person writes it: ~ for the home directory.
tilde() {
  case "$1" in
    "$HOME") printf '~' ;;
    "$HOME"/*) printf '%s/%s' '~' "${1#"$HOME"/}" ;;
    *) printf '%s' "$1" ;;
  esac
}

# ---------------------------------------------------------------------------
# The platform

npm_command() {
  printf 'npm install --global %s%s' "$CLI_PACKAGE" "${1:+@$1}"
}

unsupported() {
  fail "remote has no build for $1 yet. It runs on $SUPPORTED." \
    "With Node.js 22 or newer, the npm package may run here: $(npm_command)"
}

# Sets os, cpu (as the packages name them) and platform_label (as people do).
detect_platform() {
  uname_s=$(uname -s)
  uname_m=$(uname -m)

  case "$uname_s" in
    Darwin) os=darwin os_label=macOS ;;
    Linux) os=linux os_label=Linux ;;
    MINGW* | MSYS* | CYGWIN*)
      fail "this installer is for macOS and Linux." \
        "On Windows, run this in PowerShell: irm https://remotehost.ai/install.ps1 | iex"
      ;;
    *) unsupported "$uname_s $uname_m" ;;
  esac

  case "$uname_m" in
    arm64 | aarch64) cpu=arm64 ;;
    x86_64 | amd64) cpu=x64 ;;
    *) unsupported "$os_label $uname_m" ;;
  esac

  # A shell that Rosetta translates says x86_64 on Apple silicon. The Mac
  # itself is arm64, and that is the build to run.
  if [ "$os" = darwin ] && [ "$cpu" = x64 ]; then
    if [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || true)" = 1 ]; then
      cpu=arm64
    fi
  fi

  platform="$os-$cpu"
  platform_label="$os_label $cpu"
}

# ---------------------------------------------------------------------------
# HTTP, with curl or wget

# http_get <url> <file>: the body goes to the file, the status to
# http_status (000 when there was no answer) and the tool's own complaint,
# if it made one, to http_error.
http_get() {
  http_status=000
  http_error=""
  if has curl; then
    case "$1" in
      # Over HTTPS, a redirect may not send the download anywhere plainer.
      https://*)
        http_status=$(curl -sS -L --proto '=https' --tlsv1.2 -o "$2" -w '%{http_code}' "$1" 2>"$tmp/http-error") || true
        ;;
      *)
        http_status=$(curl -sS -L -o "$2" -w '%{http_code}' "$1" 2>"$tmp/http-error") || true
        ;;
    esac
    http_error=$(head -n 1 "$tmp/http-error")
  else
    # -S prints the answer's headers on stderr; the last status line is the
    # final answer's, after any redirect.
    wget -q -S -O "$2" "$1" 2>"$tmp/http-error" || true
    http_status=$(sed -n 's/^ *HTTP\/[0-9.]* \([0-9][0-9][0-9]\).*/\1/p' "$tmp/http-error" | tail -n 1)
    if [ -z "$http_status" ]; then
      http_status=000
      http_error=$(grep -v '^ ' "$tmp/http-error" | head -n 1 || true)
    fi
  fi
  case "$http_status" in
    [0-9][0-9][0-9]) ;;
    *) http_status=000 ;;
  esac
}

# ---------------------------------------------------------------------------
# The registry's metadata
#
# One version's document, such as
# https://registry.npmjs.org/@remotehost%2Fcli-darwin-arm64/latest, is about
# 2 kB of JSON on one line. Two of its fields are read, both strings in its
# "dist" object:
#
#   "tarball":"https://registry.npmjs.org/@remotehost/cli-darwin-arm64/-/cli-darwin-arm64-2.0.0.tgz"
#   "integrity":"sha512-<88 characters of base64>"
#
# metadata_field cuts the document at every comma, brace and bracket and
# keeps the pieces that are exactly "<field>":"<value>". A quote inside a
# JSON string is written \", so text that only looks like the field inside
# another string (a description, say) starts with a backslash and is never
# such a piece; "_integrity", which the document also has, is another key.
# The caller then requires exactly one value of exactly the expected shape.

# metadata_field <field> < document: each value, one a line.
metadata_field() {
  # shellcheck disable=SC2020 # one newline for each of the five characters
  tr ',{}[]' '\n\n\n\n\n' |
    sed -n 's/^[[:space:]]*"'"$1"'"[[:space:]]*:[[:space:]]*"\([^"\\]*\)"[[:space:]]*$/\1/p'
}

# exactly_one <field> <file>: the field's one value, or nothing.
exactly_one() {
  values=$(metadata_field "$1" <"$2")
  [ -n "$values" ] || return 0
  [ "$(printf '%s\n' "$values" | wc -l | tr -d ' ')" = 1 ] || return 0
  printf '%s' "$values"
}

metadata_unreadable() {
  fail "the npm registry's answer for $package was not what this installer reads ($1)." \
    "Run this again in a minute. If it keeps happening, tell us: $ISSUES"
}

# Reads the document in metadata.json. Sets tarball, integrity_base64 and version.
read_metadata() {
  tarball=$(exactly_one tarball "$tmp/metadata.json")
  integrity=$(exactly_one integrity "$tmp/metadata.json")

  # The tarball is this package's own, on the registry that was asked: its
  # name gives the version the tag resolved to.
  prefix="$REGISTRY/$package/-/cli-$platform-"
  case "$tarball" in
    "$prefix"*.tgz) ;;
    *) metadata_unreadable "no tarball of its own" ;;
  esac
  version=${tarball#"$prefix"}
  version=${version%.tgz}
  case "$version" in
    "" | [!0-9]* | *[!0-9A-Za-z.-]*) metadata_unreadable "no version in its tarball's name" ;;
  esac

  case "$integrity" in
    sha512-*) ;;
    *) metadata_unreadable "no sha512 checksum" ;;
  esac
  integrity_base64=$(sha512_base64 "$integrity")
  [ -n "$integrity_base64" ] || metadata_unreadable "a malformed sha512 checksum"
}

# sha512_base64 <integrity>: the base64 of an "sha512-<base64>" integrity, or
# nothing when it is not one. sha512's 64 bytes are 86 characters of the
# base64 alphabet and two of padding.
sha512_base64() {
  case "$1" in
    sha512-*) ;;
    *) return 0 ;;
  esac
  digest=${1#sha512-}
  [ "${#digest}" = 88 ] || return 0
  case "${digest%==}" in
    "$digest" | *[!A-Za-z0-9+/]*) return 0 ;;
  esac
  printf '%s' "$digest"
}

# download <url> <file> <what>: fetches the url into the file, and fails,
# naming what it was, unless the registry answered 200.
download() {
  http_get "$1" "$2"
  case "$http_status" in
    200) ;;
    000)
      fail "the download of $3 stopped.${http_error:+ $http_error}" \
        "Check your connection and run this again."
      ;;
    *)
      fail "the npm registry (${REGISTRY#*://}) answered $http_status for $3." \
        "That is on its side. Run this again in a minute."
      ;;
  esac
}

# ---------------------------------------------------------------------------
# The checksum

# sha512_hex <file>
sha512_hex() {
  if has sha512sum; then
    sha512sum "$1" | cut -d ' ' -f 1
  elif has shasum; then
    shasum -a 512 "$1" | cut -d ' ' -f 1
  elif has openssl; then
    openssl dgst -sha512 -r "$1" | cut -d ' ' -f 1
  fi
}

# base64_hex <base64>: the bytes it encodes, as hex. base64's decode flag is
# -d everywhere but older macOS, where it is -D.
base64_hex() {
  {
    if has base64; then
      printf '%s\n' "$1" | base64 -d 2>/dev/null || printf '%s\n' "$1" | base64 -D 2>/dev/null
    elif has openssl; then
      printf '%s\n' "$1" | openssl base64 -d -A
    fi
  } | od -An -v -tx1 | tr -d ' \n'
}

# ---------------------------------------------------------------------------
# The signature (the header says when it is checked)

# has_cosign: cosign is on PATH and runs. One that cannot be run, as a shell
# says with 126 or 127 (a version manager's shim with no version behind it,
# say), is no cosign; any other answer is, and its check decides.
has_cosign() {
  has cosign || return 1
  cosign_status=0
  cosign version </dev/null >/dev/null 2>&1 || cosign_status=$?
  [ "$cosign_status" != 126 ] && [ "$cosign_status" != 127 ]
}

# check_signature: checks $tmp/remote.tgz's signature, when this machine can
# (Linux, a cosign that runs, a key in COSIGN_PUBLIC_KEY), and sets
# signature_checked to yes; any miss fails. Otherwise it sets no.
check_signature() {
  signature_checked=no
  [ "$os" = linux ] && [ -n "$COSIGN_PUBLIC_KEY" ] && has_cosign || return 0

  # The same release's @remotehost/cli, which carries the signature.
  download "$REGISTRY/@remotehost%2Fcli/$version" "$tmp/cli.json" "remote $version's signature"
  cli_tarball=$(exactly_one tarball "$tmp/cli.json")
  cli_base64=$(sha512_base64 "$(exactly_one integrity "$tmp/cli.json")")
  if [ "$cli_tarball" != "$REGISTRY/$CLI_PACKAGE/-/cli-$version.tgz" ] || [ -z "$cli_base64" ]; then
    fail "the npm registry's answer for $CLI_PACKAGE $version, which holds the signature, was not what this installer reads." \
      "Run this again in a minute. If it keeps happening, tell us: $ISSUES"
  fi

  download "$cli_tarball" "$tmp/cli.tgz" "remote $version's signature"
  if [ "$(base64_hex "$cli_base64")" != "$(sha512_hex "$tmp/cli.tgz")" ]; then
    fail "the download of remote $version's signature is not the one the npm registry lists, so nothing was installed." \
      "Run this again. If it keeps happening, tell us: $ISSUES"
  fi

  mkdir "$tmp/cli"
  bundle=$tmp/cli/package/signatures/$platform.sigstore.json
  if ! tar -xzf "$tmp/cli.tgz" -C "$tmp/cli" "package/signatures/$platform.sigstore.json" 2>/dev/null ||
    [ ! -f "$bundle" ] || [ -L "$bundle" ]; then
    case "$requested" in
      # A version: one from before the signatures.
      [0-9]*)
        fail "remote $version carries no signature for $platform_label, so it was not installed." \
          "Releases from before the signatures have none: set REMOTEHOST_VERSION to a later one."
        ;;
      # A tag (latest, beta): its newest release is not signed yet.
      *)
        fail "remote $version, the newest $requested release, carries no signature for $platform_label, so it was not installed." \
          "It is not signed yet: signed releases start with REM-7008. Tell us: $ISSUES"
        ;;
    esac
  fi

  printf '%s\n' "$COSIGN_PUBLIC_KEY" >"$tmp/cosign.pub"
  # cosign 3 reads the bundle as it is; cosign 2.4 and later need
  # --new-bundle-format, which cosign 3 still accepts.
  if ! cosign verify-blob --key "$tmp/cosign.pub" --bundle "$bundle" --insecure-ignore-tlog "$tmp/remote.tgz" \
    </dev/null >"$tmp/cosign-said" 2>&1 &&
    ! cosign verify-blob --key "$tmp/cosign.pub" --bundle "$bundle" --new-bundle-format --insecure-ignore-tlog "$tmp/remote.tgz" \
      </dev/null >>"$tmp/cosign-said" 2>&1; then
    fail "the download's signature does not verify against RemoteHost's release key, so it was not installed." \
      "cosign said: $(grep -v '^WARNING' "$tmp/cosign-said" | tail -n 1)" \
      "cosign 2.4 or newer reads the signature. Run this again, and if it keeps happening, tell us: $ISSUES"
  fi
  signature_checked=yes
}

# ---------------------------------------------------------------------------
# After the install

# named <what `remote --version` printed>: "remote 2.0.0". It prints the
# version alone.
named() {
  case "$1" in
    "" | remote*) printf '%s' "$1" ;;
    *) printf 'remote %s' "$1" ;;
  esac
}

# The line that puts the install directory on PATH, for this person's shell.
path_help() {
  shown=$(tilde "$install_dir")
  # In the line itself, $HOME stays a variable.
  case "$install_dir" in
    "$HOME"/*) in_line="\$HOME/${install_dir#"$HOME"/}" ;;
    *) in_line=$install_dir ;;
  esac

  case "${SHELL##*/}" in
    zsh | bash | fish) how="To add it, run:" ;;
    *) how="To add it, put this line in your shell's startup file:" ;;
  esac
  say
  say "  $shown is not on your PATH yet. $how"
  say
  case "${SHELL##*/}" in
    zsh)
      say "    echo 'export PATH=\"$in_line:\$PATH\"' >> $(tilde "${ZDOTDIR:-$HOME}/.zshrc")"
      ;;
    bash)
      # Terminal on macOS starts bash as a login shell, which reads
      # .bash_profile; a Linux terminal's bash reads .bashrc.
      if [ "$os" = darwin ]; then rc=.bash_profile; else rc=.bashrc; fi
      say "    echo 'export PATH=\"$in_line:\$PATH\"' >> $(tilde "$HOME/$rc")"
      ;;
    fish)
      say "    fish_add_path \"$in_line\""
      ;;
    *)
      say "    export PATH=\"$in_line:\$PATH\""
      ;;
  esac
}

# Another `remote` that a shell would find first, or beside this one: says
# so, with the one command that removes it when npm installed it.
other_install_help() {
  other=$(command -v remote 2>/dev/null || true)
  case "$other" in
    /*) ;;
    *) return 0 ;;
  esac
  [ "$other" != "$install_dir/remote" ] || return 0
  listed=$(ls -l "$other" 2>/dev/null || true)
  # This install by another name: a link to it.
  case "$listed" in
    *" -> $install_dir/remote") return 0 ;;
  esac

  if [ "$on_path" = yes ]; then
    order="comes before this one on your PATH, so it is the one that runs"
  else
    order="is also installed"
  fi

  say
  # npm links a global package's command into its node_modules.
  case "$listed" in
    *node_modules/@remotehost/cli/*)
      say "  An npm-installed remote at $(tilde "$other") $order."
      say "  Remove it, so there is one remote:"
      say
      say "    npm uninstall --global $CLI_PACKAGE"
      ;;
    *)
      say "  Another remote at $(tilde "$other") $order."
      say "  Remove it, or put $(tilde "$install_dir") ahead of it on your PATH."
      ;;
  esac
}

# ---------------------------------------------------------------------------

main() {
  setup_colors
  trap cleanup EXIT
  trap 'exit 130' INT
  trap 'exit 143' TERM

  say "${bold}Installing the RemoteHost CLI${reset}"

  requested=${REMOTEHOST_VERSION:-latest}
  # v2.0.0 is 2.0.0.
  case "$requested" in
    v[0-9]*) requested=${requested#v} ;;
  esac
  case "$requested" in
    "" | *[!0-9A-Za-z._-]*)
      fail "REMOTEHOST_VERSION is \"$requested\", which is not a version or a tag." \
        "Use a version such as 2.0.0 or a tag such as beta, or leave it unset for the latest release."
      ;;
  esac

  if [ -n "${REMOTEHOST_INSTALL_DIR:-}" ]; then
    install_dir=$REMOTEHOST_INSTALL_DIR
  elif [ -n "${HOME:-}" ]; then
    install_dir=$HOME/.remotehost/bin
  else
    fail "HOME is not set, so there is no home directory to install into." \
      "Set REMOTEHOST_INSTALL_DIR to a directory and run this again."
  fi
  # tilde() compares paths with it; with none, no path is under it.
  HOME=${HOME:-/nonexistent}

  detect_platform
  package="$CLI_PACKAGE-$platform"

  has curl || has wget ||
    fail "this installer downloads with curl or wget, and neither is installed." \
      "Install curl and run this again."
  has tar ||
    fail "this installer unpacks with tar, which is not installed." \
      "Install tar and run this again."

  tmp=$(mktemp -d "${TMPDIR:-/tmp}/remotehost-install.XXXXXX") ||
    fail "could not make a temporary directory in ${TMPDIR:-/tmp}." \
      "Set TMPDIR to a directory you can write to and run this again."

  # The version, from the platform package (the header says why).
  http_get "$REGISTRY/@remotehost%2Fcli-$platform/$requested" "$tmp/metadata.json"
  case "$http_status" in
    200) ;;
    404)
      fail "there is no remote $requested for $platform_label." \
        "A release from before 2.0.0 is a Node.js program, which npm installs: $(npm_command "$requested")" \
        "Every release: https://www.npmjs.com/package/$CLI_PACKAGE?activeTab=versions"
      ;;
    000)
      fail "could not reach the npm registry (${REGISTRY#*://}).${http_error:+ $http_error}" \
        "Check your connection, and any proxy or firewall, and run this again."
      ;;
    *)
      fail "the npm registry (${REGISTRY#*://}) answered $http_status." \
        "That is on its side. Run this again in a minute."
      ;;
  esac
  read_metadata

  say
  step "Downloading remote $version for $platform_label"
  download "$tarball" "$tmp/remote.tgz" "remote $version"

  # Checked before anything is unpacked.
  expected=$(base64_hex "$integrity_base64")
  actual=$(sha512_hex "$tmp/remote.tgz")
  if [ "${#expected}" != 128 ] || [ "${#actual}" != 128 ]; then
    fail "nothing here can check the download's sha512 checksum, so it was not installed." \
      "Install coreutils (sha512sum and base64) or openssl, and run this again."
  fi
  if [ "$expected" != "$actual" ]; then
    fail "the download's checksum is not the one the npm registry lists, so it was not installed." \
      "expected sha512 $expected" \
      "received sha512 $actual" \
      "Run this again. If it keeps happening, tell us: $ISSUES"
  fi
  step "Verified its sha512 checksum"

  # Also checked before anything is unpacked.
  check_signature
  [ "$signature_checked" = no ] || step "Verified its signature with cosign"

  mkdir "$tmp/unpacked"
  tar -xzf "$tmp/remote.tgz" -C "$tmp/unpacked" package/bin/remote 2>"$tmp/tar-error" ||
    fail "could not unpack remote $version: $(head -n 1 "$tmp/tar-error")" \
      "Run this again. If it keeps happening, tell us: $ISSUES"
  program=$tmp/unpacked/package/bin/remote
  if [ ! -f "$program" ] || [ -L "$program" ]; then
    fail "remote $version's package holds no program." \
      "Tell us: $ISSUES"
  fi

  # The network helper, when this release's tarball holds one (the header
  # says which do). Read from the tarball's own list, so a release with
  # none is told apart from one that could not be unpacked.
  helper=""
  tar -tzf "$tmp/remote.tgz" >"$tmp/members" 2>"$tmp/tar-error" ||
    fail "could not read remote $version's package: $(head -n 1 "$tmp/tar-error")" \
      "Run this again. If it keeps happening, tell us: $ISSUES"
  while IFS= read -r member; do
    [ "$member" != "package/bin/$HELPER" ] || helper=$tmp/unpacked/package/bin/$HELPER
  done <"$tmp/members"
  if [ -n "$helper" ]; then
    tar -xzf "$tmp/remote.tgz" -C "$tmp/unpacked" "package/bin/$HELPER" 2>"$tmp/tar-error" ||
      fail "could not unpack remote $version's network helper: $(head -n 1 "$tmp/tar-error")" \
        "Run this again. If it keeps happening, tell us: $ISSUES"
    if [ ! -f "$helper" ] || [ -L "$helper" ]; then
      fail "remote $version's network helper is not a program." \
        "Nothing was installed. Tell us: $ISSUES"
    fi
  fi

  mkdir -p "$install_dir" 2>/dev/null ||
    fail "could not create $(tilde "$install_dir")." \
      "Set REMOTEHOST_INSTALL_DIR to a directory you can write to and run this again."
  install_dir=$(CDPATH='' cd -- "$install_dir" && pwd)

  before=""
  if [ -x "$install_dir/remote" ]; then
    before=$(named "$("$install_dir/remote" --version </dev/null 2>/dev/null || true)")
  fi

  # Written beside its destination and renamed onto it, so `remote` is the
  # old program or the new one at every moment, and a shell running the old
  # one keeps running it.
  staged=$install_dir/.remote.installing.$$
  if ! cp "$program" "$staged" 2>/dev/null || ! chmod 755 "$staged"; then
    fail "could not write to $(tilde "$install_dir")." \
      "Set REMOTEHOST_INSTALL_DIR to a directory you can write to and run this again."
  fi

  # It has to run here before it replaces what is there.
  after=$("$staged" --version </dev/null 2>"$tmp/run-error") ||
    fail "remote $version does not run on this machine: $(head -n 1 "$tmp/run-error")" \
      "Nothing was changed${before:+: $before is still installed}." \
      "Tell us what machine this is: $ISSUES"

  after=$(named "$after")

  # The helper is held to the same: staged beside its destination, and run
  # before anything is replaced.
  if [ -n "$helper" ]; then
    staged_helper=$install_dir/.$HELPER.installing.$$
    if ! cp "$helper" "$staged_helper" 2>/dev/null || ! chmod 755 "$staged_helper"; then
      fail "could not write to $(tilde "$install_dir")." \
        "Set REMOTEHOST_INSTALL_DIR to a directory you can write to and run this again."
    fi
    "$staged_helper" --version </dev/null >/dev/null 2>"$tmp/run-error" ||
      fail "remote $version's network helper does not run on this machine: $(head -n 1 "$tmp/run-error")" \
        "Nothing was changed${before:+: $before is still installed}." \
        "Tell us what machine this is: $ISSUES"
  fi

  mv -f "$staged" "$install_dir/remote"
  staged=""

  # This release's helper beside it, or none: one an earlier install left
  # belongs to that release, and remote would start it.
  if [ -n "$staged_helper" ]; then
    mv -f "$staged_helper" "$install_dir/$HELPER"
    staged_helper=""
  else
    rm -f "$install_dir/$HELPER"
  fi

  # rh, the short name, is a link to it.
  staged_link=$install_dir/.rh.installing.$$
  rm -f "$staged_link"
  ln -s remote "$staged_link"
  mv -f "$staged_link" "$install_dir/rh"
  staged_link=""

  step "Installed $(tilde "$install_dir/remote"), with rh as its short name"
  [ -z "$helper" ] ||
    step "Installed $(tilde "$install_dir/$HELPER"), which remote network join --mode rootless runs"
  say

  if [ -z "$before" ]; then
    say "  ${green}${after}${reset}"
  elif [ "$before" = "$after" ]; then
    say "  ${green}${after}${reset} ${dim}(already the installed version; installed again)${reset}"
  else
    say "  ${green}${after}${reset} ${dim}(was ${before})${reset}"
  fi

  case ":${PATH:-}:" in
    *":$install_dir:"*) on_path=yes ;;
    *) on_path=no ;;
  esac
  [ "$on_path" = yes ] || path_help
  other_install_help

  say
  if [ "$on_path" = yes ]; then
    say "Next: ${bold}remote login${reset}"
  else
    say "Then open a new terminal and run: ${bold}remote login${reset}"
  fi
}

# Tests read the functions above without running an install.
[ -n "${REMOTEHOST_INSTALL_TEST_SOURCE:-}" ] || main
