#!/usr/bin/env bash
# Install the TestFlows Machine client.
#
#   curl https://testflows.com/machine/install -fsS | bash
#
# The client is given to a TestFlows account. The script signs in, or creates an account,
# at the terminal: an email, and a code sent to it. The Client EULA licenses the
# client, https://testflows.com/machine/legal/client-eula/, and is part of the
# Agreement with the Terms of Service. An account that has not accepted the
# current version is shown both documents in full, and accepts them before
# anything is downloaded. Without a terminal it takes an API key,
# TESTFLOWS_MACHINE_API_KEY, whose account has accepted them. It signs out when
# it ends; `machine login` signs the client in.
#
# It downloads one file, the `machine` binary, checks it against the SHA-256
# checksum published next to it, and puts it in ~/.local/bin. It also writes
# machine-env there, a shell in which `machine` is this client. It never asks for
# root. Where another program called machine is already on PATH, as /usr/bin/machine
# is on a Mac, `machine` goes to ~/.local/share/machine/bin instead, which is not on
# PATH, and ~/.local/bin holds machine-env alone. Putting ~/.local/bin on PATH then
# hides nothing. The checksum is signed with the release keys below, GPG and RSA, and the
# signature is checked before the checksum is trusted: with gpg where there is one,
# else with openssl, which every Mac has. The download itself is protected by HTTPS.
#
# It also installs the Python SDK core, the one file the SDK runs on, checked the same
# way, to ~/.testflows/machine/sdk/_testflows_machine_core.abi3.so.
#
# On first run the client unpacks itself into ~/.cache/machine/.
# After an update this script removes the folders older versions unpacked.
#
# To check a download yourself, print the checksum published for a version and
# compare it with `sha256sum` of your file:
#
#   curl https://testflows.com/machine/install -fsS | bash -s -- --checksum
#
# To see the versions there are, and install one of them:
#
#   curl https://testflows.com/machine/install -fsS | bash -s -- --list
#   curl https://testflows.com/machine/install -fsS | bash -s -- --version 20261007-2203
#
# Environment:
#   MACHINE_INSTALL_DIR   where to put machine-env, and machine when no other program
#                         called machine is on PATH (default: ~/.local/bin)
#   MACHINE_VERSION       a version to install, YYYYMMDD-HHMM (default: the latest)
#   MACHINE_NO_MODIFY_PATH  set to anything, the script does not ask to put the install
#                         directory on PATH in your shell's startup file. It asks only at
#                         a terminal, and writes only when the answer is yes.
#   TESTFLOWS_MACHINE_API_KEY
#                         an API key to install with, in place of signing in at a
#                         terminal; the client reads the same variable
#   TESTFLOWS_MACHINE_ACCESS_TOKEN
#                         the client's own sign-in, which `machine upgrade` hands over
#                         in place of signing in again; it is never signed out
#   TESTFLOWS_MACHINE_API_CA_FILE
#                         a PEM file of the CAs to trust for the API, as the client
#                         reads it; `machine upgrade` hands over the client's
#
# To upgrade an installed client, run `machine upgrade`.
#
# Everything happens inside main(), which is only called on the last line. If the
# download is cut short, bash never reaches that line and nothing runs.

# Piped into sh, which is dash on Debian and Ubuntu, the next line fails with
# "set: Illegal option -o pipefail" and names nothing the reader can act on.
# Written for any POSIX shell, since this is the one line another shell runs.
if [ -z "${BASH_VERSION:-}" ]; then
    echo "This installer needs bash." >&2
    echo "Install with curl https://testflows.com/machine/install -fsS | bash" >&2
    exit 1
fi

set -euo pipefail

# The service an account signs in to, which gives a signed-in account a link to each
# release file. Every download is signed in; there is no other source of releases.
API_URL="${TESTFLOWS_MACHINE_API_URL:-https://machine-api.testflows.com}"
BASE_URL="$API_URL"
# Rounds of proof of work a sign-in answers before it gives up: the service asks for more
# when one email is asked for often.
POW_ROUNDS=3
# Codes a person may type before the installer stops and they start again.
CODE_TRIES=3
HELPER=""
API_POW=""
API_HEADERS=""
API_BODY=""
# An empty CA directory, made when TESTFLOWS_MACHINE_API_CA_FILE names the API's CAs.
API_NO_CAS=""
API_STATUS=""
SIGNED_IN=""
ACCOUNT=""
# The Terms of Service and the Client EULA, which licenses the client: the
# Markdown of their pages on testflows.com, which the installer shows in full
# before they are accepted. Both carry the Agreement version as their date.
TERMS_URL="${MACHINE_TERMS_URL:-https://testflows.com/machine/legal/terms-of-service.md}"
TERMS_PAGE="https://testflows.com/machine/legal/terms-of-service/"
EULA_URL="${MACHINE_EULA_URL:-https://testflows.com/machine/legal/client-eula.md}"
EULA_PAGE="https://testflows.com/machine/legal/client-eula/"
# Whether a download shows a progress bar: the client's own file does, and the small
# files around it, its checksum and the version names, are fetched quietly.
FETCH_PROGRESS=false
# Whether a download keeps curl's own error to itself, for a file that may be missing.
FETCH_QUIET=false

# The release signing keys. Every release's checksum files are signed with both: the GPG
# key for gpg, the RSA key for openssl. Fingerprint 5F3621A5081FF68BFF2581FDB280231700CCCA66.
GPG_PUBLIC_KEY="$(cat <<'KEY'
-----BEGIN PGP PUBLIC KEY BLOCK-----

mQINBGq/Iq8BEADJBFZKdQx+QHDgEQW3HX+9MiiV/kiUc/uHeamYTJEjKPnkSp6n
Uu+pkwcr6vVy9GUTd7Pu8+LAqnoi37Lyt3QbMTNHBdyfTNTD6pRKojXbrh18CznV
SUYKoVDFb9yELEY47qWJec0v8XuwRAYQW8zLaWHRLemNewPMdc+ts7rcN2H8C78Q
TXAUw0XZphaAdMmetNxFY4R2TRxHAY5LBPwbGi+eSFgfqJFkVVEB8+Mfa7kWpPhy
HC9Tbd714G+sk/3YeYUOF7OEqS9tnziWQ9z/CGMDggOVdoxASdPUS7ZfCbKYbjfl
adzkcPEuw/jguwTkz3AhBzZHjgEww8JU3/jnXarJWyvujlGOawhsz07xoCgPpsEe
MmiwgIkmtw00/rVv8Ds4fjTQsBpOPSV+Z3by0OfYTeh0v0OsQFSJmYkVH1uYJGtB
FJb/xE0EqaeG0QCW4E8Sj/k7Yi+vLwlPjNAikt4pVEVG0POKzHI+AdsyO0Dx+vwJ
6sc+nSuWF/3QI7dFs4qxjbTuWrNsj6CK1bVFkqbIMKt/3W296DcvjHjeowfYgyyI
LQ4D2F/xkG/sDRVDARWPoEholVZuLFpfi4GzAOVbdO9IsWEjroZ+LZYPcKbi/SwG
1SHqXM0xhQLnWwPviJOCYUI1wVvHT9m88HON6GxcwrSZULh30qQkoh867wARAQAB
tDlUZXN0Rmxvd3MgTWFjaGluZSBDbGllbnQgUmVsZWFzZXMgPGNvbnRhY3RAdGVz
dGZsb3dzLmNvbT6JAlEEEwEKADsWIQRfNiGlCB/2i/8lgf2ygCMXAMzKZgUCar8i
rwIbAwULCQgHAgIiAgYVCgkICwIEFgIDAQIeBwIXgAAKCRCygCMXAMzKZp9JD/4q
HZZLmkpyGb2VVp7R7ODKy0WT6IlSfkLJmaeP70u18R2TCX2F2UHNVT+MldJGabhA
9iTOuegCErFK7rtA5xE/XiG/9UM3JPU1htb1bxulOjbvmXLNUBohCKq4GcY8IZkn
xpt9Yi/yd1VoOFjOvVHPFcNG3167VDEcw+Xre2i2gg8HQ6MGb2KzZ7s//i1Agib1
vShupxP1ZpyT1LxXL4mOVruP/Lzvq141kWUKGkjKjFCj0zX9RgoCooQwZROZgxQj
nOyA68PcpM7aEKQ3+42pxtQ0ENbH+Cr6blQmXv8p7BP+dHh/houOATbJv0820s9H
czvsF5+N0pW/GR1qYdv+52W8cAo02C6/UO7ao4o4zVgEoJZ2dr0UNWZ5U0IUggnL
sZSC+N7ZON9fs3bmErYACgPk9MVMM9NncAfQRLheEZwjyiJM3YhBHSFPyJgsEaUZ
ufITA0U6E7ySz5oeAWspv4+tO8TnR/6dh2dRXjicYuRAZYvcU9IRTDaOzWTT7eCr
jh3lhzextVbTBG0nOCwE1FZ9mZjxJc2Xin9CyjNKhOPDz4ohm5GqvIt93AzznFSu
vJKYDfexEZGJg6/QIFUM+1GD1dvvyizE/wOD3b4Wwty3t2mfCqosAGeAB+8fJ7d/
QqEGgIQpq4OhqE0jCNkSkJXT71WS18x+DE+QWcQ3kw==
=nKxh
-----END PGP PUBLIC KEY BLOCK-----
KEY
)"
RSA_PUBLIC_KEY="$(cat <<'KEY'
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAnqKBaOQUJL9SgeEWI1mu
Rgq7LQwXzFHuf7rmWOoqLayqyWI4N09Ce+mnmUXr66R0jBFPms4fHS3LWmsyEUsT
LIt1nj5ptib6q6piU89fhu2UMWf1dJetRq5ycny/NfjWfzjFb7BTC0fNPKGmNFwE
PaLQwItiMS3MllWdU8UQMcisJ6Mo3qVxKmHjozcY6CiezxwoPoTjrlevn/oqS9FW
SQMkmaurspM++i70MIExh2+SJBGkvlGLAKnD73vyZRGq8kxHbJJwRPsQ+Du0MMCN
uwtFsSiz93a6nqv9A9logP+wtpJPtEvzX3PpsEXNoD+0LxaR4QgoFZXXDpH6mgYj
k+RtZ/eJApHE6H3Mq8IpgPUdPKo8rbua8Y6kHqyW3o7IEwYKShLIQzQn/kzp2LoA
MIKYx9Z2Hba76g/JVsc3jPeHh7L+j7mZRjLjuO2dIPh/1ZgeWLWmlUyozidyUKsZ
FgywOOQnAsGOVZc/YTW+IGMLkxmmQU/KZt6LNXq7lzNjCnrjoj6D+jSOd9AN6FJw
ltbzBsLSdpAroNaQ0WtP+v6/DW7eyJpZScuDGDcaduI4SVLBGRtEjYB7JWdcqcCm
knYR7j6LRccvyTus2W+4NAIMgEf/2I0o2RRmjhGNfKpP9YcitqZWHmgJvmjNIbJV
EdYmQm3kt5csap5+Zr7qebkCAwEAAQ==
-----END PUBLIC KEY-----
KEY
)"
# HTTPS only, so no redirect can downgrade the download. Plain HTTP only when
# TESTFLOWS_MACHINE_API_URL names an http:// service, as a local test service.
PROTOCOLS="=https"
case "$BASE_URL" in
    http://*) PROTOCOLS="=http,https" ;;
esac
# Tries per download. A dropped connection or a 5xx is worth another; a 403 or
# 404 is not, and stops at once.
FETCH_TRIES=3

if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
    BOLD=$'\033[1m'; GREEN=$'\033[32m'; YELLOW=$'\033[33m'; RED=$'\033[31m'; DIM=$'\033[2m'; RESET=$'\033[0m'
else
    BOLD=""; GREEN=""; YELLOW=""; RED=""; DIM=""; RESET=""
fi

say()  { printf '%s\n' "$*"; }
ok()   { printf '%s✔%s %s\n' "$GREEN" "$RESET" "$*"; }
warn() { printf '%s!%s %s\n' "$YELLOW" "$RESET" "$*" >&2; }
die()  { printf '%s✗%s %s\n' "$RED" "$RESET" "$1" >&2; shift; for line in "$@"; do printf '  %s\n' "$line" >&2; done; exit 1; }

# A path with $HOME shown as ~, for messages.
tilde() {
    case "$1" in
        "${HOME:-/nonexistent}"/*) printf '~%s' "${1#"$HOME"}" ;;
        *) printf '%s' "$1" ;;
    esac
}

# The version a machine binary reports, or nothing if it doesn't run.
version_of() {
    "$1" -o json --version 2>/dev/null | sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' | head -n 1
}

# fetch URL DEST: download with curl, or wget when there is no curl, retrying a
# failure that can recover. The loop is ours rather than curl --retry, which does
# not retry a reset connection; --retry-all-errors would, but needs curl 7.71,
# newer than Ubuntu 20.04 ships.
fetch() {
    local attempt
    for ((attempt = 1; attempt <= FETCH_TRIES; attempt++)); do
        fetch_once "$1" "$2" && return 0
        [ "$FETCH_STATUS" = "final" ] && return 1
        [ "$attempt" -lt "$FETCH_TRIES" ] && { warn "The download failed. Trying again."; sleep 2; }
    done
    # BusyBox wget reaches HTTPS servers through the openssl command; its own TLS
    # is refused by the release server. Say what fixes it, not "check your connection".
    if [ "$DOWNLOADER" = "busybox-wget" ] && [ "$FETCH_STATUS" != "final" ]; then
        warn "BusyBox wget couldn't connect over HTTPS. Installing curl (or openssl) fixes"
        warn "that, for example: apk add curl"
    fi
    return 1
}

# choose_downloader: curl, else GNU wget, else BusyBox wget, which works but does
# not check the server's HTTPS certificate; that is said once, up front, so the
# person installing knows what was not checked.
choose_downloader() {
    if command -v curl >/dev/null 2>&1; then
        DOWNLOADER="curl"
    elif command -v wget >/dev/null 2>&1; then
        # Read whole first: grep -q would stop wget with SIGPIPE, which pipefail
        # reports as a failure even when the option is there.
        local help
        help="$(wget --help 2>&1 || true)"
        if [[ "$help" == *--https-only* ]]; then
            DOWNLOADER="wget"
        else
            DOWNLOADER="busybox-wget"
            warn "This wget doesn't check the server's HTTPS certificate. The download is"
            warn "still checked against its published checksum. With curl, the connection"
            warn "is checked too."
        fi
    else
        die "Neither curl nor wget is installed." "Install one of them and run this again."
    fi
}

# fetch_once URL DEST: one try. On failure FETCH_STATUS is "final" for an HTTP
# answer no retry changes (4xx but 408 and 429), else "retry".
fetch_once() {
    FETCH_STATUS="retry"
    if [ "$DOWNLOADER" = "curl" ]; then
        local progress="-sS" code
        $FETCH_QUIET && progress="-s"
        $FETCH_PROGRESS && [ -t 2 ] && progress="--progress-bar"
        if code="$(curl -fL --proto "$PROTOCOLS" --proto-redir "$PROTOCOLS" --tlsv1.2 \
            --connect-timeout 15 $progress -w '%{http_code}' -o "$2" "$1")"; then
            return 0
        fi
        case "$code" in
            408 | 429) ;;
            4??) FETCH_STATUS="final" ;;
        esac
        return 1
    elif [ "$DOWNLOADER" = "wget" ]; then
        local https_only=()
        [ "$PROTOCOLS" = "=https" ] && https_only=(--https-only)
        # ${...[@]+...}: macOS runs this under bash 3.2, where set -u calls an empty array
        # unbound.
        wget -q --tries=1 --timeout=15 ${https_only[@]+"${https_only[@]}"} -O "$2" "$1"
    else
        wget -q -T 15 -O "$2" "$1"
    fi
}

usage() {
    cat <<'USAGE'
Install the TestFlows Machine client.

  curl https://testflows.com/machine/install -fsS | bash
  curl https://testflows.com/machine/install -fsS | bash -s -- --list
  curl https://testflows.com/machine/install -fsS | bash -s -- --version 20261007-2203

Options:
  --list          list the versions there are, newest first, instead of installing
  --version V     install version V, YYYYMMDD-HHMM, instead of the latest; V is
                  installed even when it is installed already
  --checksum      print the published SHA-256 checksum instead of installing
  --download      download this system's file, its checksum and their signatures
                  into the current folder instead of installing, to check by hand
  --no-signature  install without checking the release signature
  --no-checksum   install without checking the checksum, or the signature
  -h, --help      show this help

The client is given to a TestFlows account. The installer signs in, or creates an
account, with an email and a code sent to it. The Client EULA licenses the client.
An account accepts the current Agreement, which the installer shows in full, before
anything is downloaded: https://testflows.com/machine/legal/client-eula/

Environment:
  MACHINE_INSTALL_DIR   where to put machine-env, and machine when no other program
                        called machine is on PATH (default: ~/.local/bin)
  MACHINE_VERSION       a version to use, as --version names one
  TESTFLOWS_MACHINE_API_KEY
                        an API key to install with, where there is no terminal to
                        sign in at; the client reads the same variable. Its account
                        must have accepted the current Agreement.
  TESTFLOWS_MACHINE_ACCESS_TOKEN
                        the client's own sign-in, which machine upgrade hands over;
                        the client stays signed in
  TESTFLOWS_MACHINE_API_CA_FILE
                        a PEM file of the CAs to trust for the API, as the client
                        reads it
  MACHINE_NO_MODIFY_PATH  set to anything, do not ask to put the directory on PATH
USAGE
}

# show_terms FILE TITLE: a legal document's whole text, at the terminal, to read
# before it is accepted. FILE is its page's own Markdown from testflows.com, so
# the text read is the text published; it is shown in a pager the person scrolls.
show_terms() {
    local text pager
    text="$(mktemp)" || die "Could not create a temporary file."
    terms_plain "$1" > "$text"
    if command -v less >/dev/null 2>&1; then
        # In a less prompt a full stop is special and is written \.
        pager=(less -R -P "${2:-The Terms of Service}\. Space scrolls, q when read\.")
    elif command -v more >/dev/null 2>&1; then
        pager=(more)
    else
        pager=(cat)
    fi
    "${pager[@]}" "$text" < /dev/tty > /dev/tty || cat "$text" > /dev/tty
    rm -f "$text"
}

# terms_plain FILE: the Terms' Markdown as plain text: no HTML, no emphasis marks, a link
# as its text and its address.
terms_plain() {
    if [ "$HELPER" = "perl" ]; then
        perl -0777 -pe '
            s/<!--.*?-->\n?//gs; s/<[^>]+>//g;
            s/\[([^\]]+)\]\((\/[^)]*)\)/$1 (https:\/\/testflows.com$2)/g;
            s/\[([^\]]+)\]\(([^)]*)\)/$1 ($2)/g;
            s/\*\*([^*]+)\*\*/$1/g; s/`([^`]+)`/$1/g; s/^#+ //mg;' "$1"
    else
        python3 -c '
import re, sys
t = open(sys.argv[1], encoding="utf-8").read()
t = re.sub(r"<!--.*?-->\n?", "", t, flags=re.S)
t = re.sub(r"<[^>]+>", "", t)
t = re.sub(r"\[([^\]]+)\]\((/[^)]*)\)", r"\1 (https://testflows.com\2)", t)
t = re.sub(r"\[([^\]]+)\]\(([^)]*)\)", r"\1 (\2)", t)
t = re.sub(r"\*\*([^*]+)\*\*", r"\1", t)
t = re.sub(r"`([^`]+)`", r"\1", t)
t = re.sub(r"^#+ ", "", t, flags=re.M)
sys.stdout.write(t)' "$1"
    fi
}

# version_valid VERSION: whether it is a release version, YYYYMMDD-HHMM.
version_valid() {
    case "$1" in
        [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]) return 0 ;;
        *) return 1 ;;
    esac
}

# choose_helper: perl or python3, which work out the sign-in's proof of work and read the
# service's answers. bash has neither SHA-256 nor JSON.
choose_helper() {
    if command -v perl >/dev/null 2>&1 && perl -MDigest::SHA -MJSON::PP -e 1 2>/dev/null; then
        HELPER="perl"
    elif command -v python3 >/dev/null 2>&1; then
        HELPER="python3"
    else
        die "Signing in needs perl or python3, and neither is installed." \
            "Install python3 and run this again." \
            "Or install with an API key curl https://testflows.com/machine/install -fsS | TESTFLOWS_MACHINE_API_KEY=<key> bash"
    fi
}

# json_get FILE KEY: a top-level value of a JSON object, true or false for a boolean;
# fails when it is not there.
json_get() {
    if [ "$HELPER" = "perl" ]; then
        perl -MJSON::PP -e '
            local $/; open(my $f, "<", $ARGV[0]) or exit 1;
            my $d = eval { decode_json(<$f>) }; exit 1 unless ref($d) eq "HASH";
            my $v = $d->{$ARGV[1]}; exit 1 unless defined $v;
            print JSON::PP::is_bool($v) ? ($v ? "true" : "false") : $v;' "$1" "$2"
    else
        python3 -c '
import json, sys
try:
    d = json.load(open(sys.argv[1]))
except ValueError:
    sys.exit(1)
v = d.get(sys.argv[2]) if isinstance(d, dict) else None
if v is None:
    sys.exit(1)
print(("true" if v else "false") if isinstance(v, bool) else v, end="")' "$1" "$2"
    fi
}

# json_object KEY VALUE...: a JSON object of string values, quoted as JSON quotes them:
# an email is typed by a person and may hold anything.
json_object() {
    if [ "$HELPER" = "perl" ]; then
        perl -MJSON::PP -e 'my %d = @ARGV; print JSON::PP->new->canonical->encode(\%d)' "$@"
    else
        python3 -c 'import json, sys; a = sys.argv[1:]; print(json.dumps(dict(zip(a[::2], a[1::2]))), end="")' "$@"
    fi
}

# pow_solve SUBJECT BITS BUCKET_SECONDS: a stamp whose SHA-256 has BITS leading zero bits,
# as the service asks of a sign-in so that a flood of them costs work.
pow_solve() {
    if [ "$HELPER" = "perl" ]; then
        perl -MDigest::SHA=sha256 -e '
            my ($subject, $bits, $secs) = @ARGV;
            my $bucket = int(time() / $secs);
            my $rand = join "", map { sprintf "%02x", int(rand(256)) } 1 .. 8;
            my $prefix = "1:$bits:$bucket:$subject:$rand:";
            my ($whole, $rest) = (int($bits / 8), $bits % 8);
            for (my $n = 0; ; $n++) {
                my $h = sprintf "%x", $n;
                my $d = sha256($prefix . $h);
                next if substr($d, 0, $whole) ne ("\0" x $whole);
                next if $rest && (ord(substr($d, $whole, 1)) >> (8 - $rest));
                print "1:$bits:$bucket:$rand:$h";
                last;
            }' "$1" "$2" "$3"
    else
        python3 -c '
import hashlib, secrets, sys, time
subject, bits, secs = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
bucket = int(time.time()) // secs
rand = secrets.token_hex(8)
prefix = hashlib.sha256(f"1:{bits}:{bucket}:{subject}:{rand}:".encode())
limit = 1 << (256 - bits)
n = 0
while True:
    h = prefix.copy()
    h.update(format(n, "x").encode())
    if int.from_bytes(h.digest(), "big") < limit:
        break
    n += 1
print("1:%d:%d:%s:%x" % (bits, bucket, rand, n), end="")' "$1" "$2" "$3"
    fi
}

# api_call METHOD PATH [BODY]: one request to the service, its answer in API_BODY and its
# status in API_STATUS, 000 when there was none. The token rides in a header file, never
# on a command line, where ps shows it to every user of the system.
api_call() {
    local method="$1" path="$2" body="${3:-}" args=()
    : > "$API_BODY"
    args=(-sS -X "$method" --proto "$PROTOCOLS" --tlsv1.2 --connect-timeout 15
        -A "machine-install" -H "Accept: application/json" -H @"$API_HEADERS"
        -o "$API_BODY" -w '%{http_code}')
    [ -z "$API_POW" ] || args+=(-H "X-Tf-Pow: $API_POW")
    [ -z "$body" ] || args+=(-H "Content-Type: application/json" --data-binary "$body")
    # The CAs the client trusts for the API, which machine upgrade hands over with its
    # sign-in: its token then meets only the API the client itself would talk to. An
    # empty --capath as well, since curl reads its default CA directory beside --cacert.
    [ -z "$API_NO_CAS" ] || args+=(--cacert "$TESTFLOWS_MACHINE_API_CA_FILE" --capath "$API_NO_CAS")
    API_STATUS="$(curl "${args[@]}" "$API_URL$path" 2>/dev/null)" || API_STATUS="${API_STATUS:-000}"
}

# api_pow METHOD PATH BODY: api_call, answering the service's proof-of-work challenge,
# again when it asks for more work, at most POW_ROUNDS times.
api_pow() {
    local round subject bits secs
    API_POW=""
    api_call "$1" "$2" "$3"
    for ((round = 0; round < POW_ROUNDS; round++)); do
        [ "$API_STATUS" = "400" ] || break
        [ "$(json_get "$API_BODY" error 2>/dev/null)" = "proof_of_work_required" ] || break
        subject="$(json_get "$API_BODY" subject)" || break
        bits="$(json_get "$API_BODY" required_difficulty)" || break
        secs="$(json_get "$API_BODY" bucket_seconds)" || break
        API_POW="$(pow_solve "$subject" "$bits" "$secs")"
        api_call "$1" "$2" "$3"
    done
    API_POW=""
}

# api_refusal: the service's own words for a refusal, or what failed without them.
api_refusal() {
    json_get "$API_BODY" error 2>/dev/null \
        || { [ "$API_STATUS" = "000" ] && printf 'The service could not be reached.'; } \
        || printf 'The service answered %s.' "$API_STATUS"
}

# ask PROMPT: a line typed at the terminal. With curl | bash the script is standard
# input, so the answer is read from the terminal itself.
ask() {
    printf '%s➤%s %s' "$BOLD" "$RESET" "$1" > /dev/tty
    IFS= read -r ANSWER < /dev/tty || ANSWER=""
}

# asked_yes PROMPT: whether the answer is yes.
asked_yes() {
    ask "$1"
    case "$ANSWER" in y | Y | yes | Yes | YES) return 0 ;; esac
    return 1
}

# sign_in: an account, by an API key in TESTFLOWS_MACHINE_API_KEY, or by a person at the terminal
# signing in or signing up. Every release file is given to an account alone, so each copy
# of the client handed out names one.
sign_in() {
    API_HEADERS="$(mktemp)" || die "Could not create a temporary file."
    API_BODY="$(mktemp)" || die "Could not create a temporary file."
    chmod 600 "$API_HEADERS"
    if [ -n "${TESTFLOWS_MACHINE_API_CA_FILE:-}" ]; then
        [ -r "$TESTFLOWS_MACHINE_API_CA_FILE" ] || die "TESTFLOWS_MACHINE_API_CA_FILE names no file to read: $TESTFLOWS_MACHINE_API_CA_FILE"
        API_NO_CAS="$(mktemp -d)" || die "Could not create a temporary directory."
    fi
    if [ -n "${TESTFLOWS_MACHINE_API_KEY:-}" ]; then
        printf 'Authorization: Bearer %s\n' "$TESTFLOWS_MACHINE_API_KEY" > "$API_HEADERS"
        SIGNED_IN="api"
        return 0
    fi
    # machine upgrade hands over the client's own sign-in. It is the client's, so the
    # installer never signs it out, and a person at the terminal accepts a new Agreement.
    if [ -n "${TESTFLOWS_MACHINE_ACCESS_TOKEN:-}" ]; then
        printf 'Authorization: Bearer %s\n' "$TESTFLOWS_MACHINE_ACCESS_TOKEN" > "$API_HEADERS"
        SIGNED_IN="client"
        return 0
    fi
    ( : < /dev/tty ) 2>/dev/null || die "Installing the client needs a sign-in, and there is no terminal to ask at." \
        "Install with an API key curl https://testflows.com/machine/install -fsS | TESTFLOWS_MACHINE_API_KEY=<key> bash"
    say "To install the client, sign in to your TestFlows account or sign up for one."
    local email new
    while :; do
        ask "Do you have an account? [y/n] "
        case "$ANSWER" in
            y | Y | yes | Yes | YES) new=false; break ;;
            n | N | no | No | NO) new=true; break ;;
        esac
    done
    while :; do
        ask "Email: "
        email="$(printf '%s' "$ANSWER" | tr -d ' \t')"
        case "$email" in ?*@?*.?*) break ;; esac
        warn "That is not an email address."
    done
    if $new; then
        local version
        api_call GET /terms/current
        [ "$API_STATUS" = "200" ] || die "Could not read the Agreement's version. $(api_refusal)"
        version="$(json_get "$API_BODY" version)"
        read_agreement "$version"
        say "Creating an account for $email"
        api_pow POST /signup/start "$(json_object email "$email" terms_version "$version")"
        [ "$API_STATUS" = "204" ] || die "The account was not created. $(api_refusal)"
        ask "Open the link we sent to $email to confirm it, then press Enter. "
    fi
    sign_in_code "$email"
    ok "Signed in as $email"
    ACCOUNT="$email"
}

# sign_in_code EMAIL: send a sign-in code to EMAIL and take it from the terminal, at
# most CODE_TRIES times; r sends a new code.
sign_in_code() {
    local email="$1" try code token
    say "Sending a sign-in code to $email"
    api_pow POST /login/start "$(json_object email "$email")"
    [ "$API_STATUS" = "204" ] || die "No code was sent. $(api_refusal)"
    for ((try = 1; try <= CODE_TRIES; try++)); do
        ask "Code, or r to send a new one: "
        code="$(printf '%s' "$ANSWER" | tr -d ' \t')"
        if [ "$code" = "r" ]; then
            api_pow POST /login/start "$(json_object email "$email")"
            [ "$API_STATUS" = "204" ] || die "No code was sent. $(api_refusal)"
            say "Sent a new code to $email"
            try=$((try - 1))
            continue
        fi
        [ -n "$code" ] || { try=$((try - 1)); continue; }
        api_pow POST /login/verify "$(json_object email "$email" code "$code")"
        if [ "$API_STATUS" = "200" ] && token="$(json_get "$API_BODY" access_token)"; then
            printf 'Authorization: Bearer %s\n' "$token" > "$API_HEADERS"
            SIGNED_IN="access"
            return 0
        fi
        [ "$API_STATUS" = "400" ] || die "Not signed in. $(api_refusal)"
        warn "That code is not right, or it expired."
    done
    die "Not signed in." "Run the installer again to send a new code."
}

# agreement_version_of FILE: the Agreement version a legal text carries, from
# its "Agreement version:" line; nothing when it has none. The version, not the
# date, is what an acceptance records, so a text cannot change under one version.
agreement_version_of() {
    if [ "$HELPER" = "perl" ]; then
        perl -0777 -ne 'print $1 if /Agreement version:\s*([0-9A-Za-z.-]+)/' "$1"
    else
        python3 -c '
import re, sys
found = re.search(r"Agreement version:\s*([0-9A-Za-z.-]+)", open(sys.argv[1], encoding="utf-8").read())
if found:
    print(found.group(1), end="")' "$1"
    fi
}

# read_agreement VERSION: show the published Terms of Service and Client EULA,
# both of which must be VERSION, and ask for their acceptance. Another version
# means a text is being changed, and accepting it now would accept words not read.
read_agreement() {
    local version="$1" terms eula
    terms="$(mktemp)" || die "Could not create a temporary file."
    eula="$(mktemp)" || { rm -f "$terms"; die "Could not create a temporary file."; }
    fetch "$TERMS_URL" "$terms" || { rm -f "$terms" "$eula"; die "Could not download the Terms of Service." "Check your connection and try again."; }
    fetch "$EULA_URL" "$eula" || { rm -f "$terms" "$eula"; die "Could not download the Client EULA." "Check your connection and try again."; }
    if [ "$(agreement_version_of "$terms")" != "$version" ] || [ "$(agreement_version_of "$eula")" != "$version" ]; then
        rm -f "$terms" "$eula"
        die "The Terms of Service and Client EULA are being updated. Try again shortly."
    fi
    say "The Terms of Service of $version follow, as at $TERMS_PAGE"
    show_terms "$terms" "The Terms of Service"
    say "The Client EULA of $version follows, as at $EULA_PAGE"
    say "It licenses the client. Read it, then accept both documents or not."
    show_terms "$eula" "The Client EULA"
    rm -f "$terms" "$eula"
    asked_yes "Accept the Terms of Service and the Client EULA of $version? [y/N] " \
        || die "The client is not installed. It needs the Terms of Service and the Client EULA accepted."
}

# accept_terms: the account's acceptance of the current Terms of Service, asked for when it
# has none. A person accepts; an API key's account must have accepted already.
accept_terms() {
    local version accepted
    api_call GET /terms
    if [ "$API_STATUS" = "401" ] && [ "$SIGNED_IN" = "client" ]; then
        die "The client's sign-in has ended." "Sign in again machine login"
    fi
    [ "$API_STATUS" = "200" ] || die "Could not read the Agreement's version. $(api_refusal)"
    version="$(json_get "$API_BODY" version)"
    accepted="$(json_get "$API_BODY" accepted)"
    [ "$accepted" = "true" ] && return 0
    if [ "$SIGNED_IN" = "api" ]; then
        die "This API key's account has not accepted the Agreement of $version." \
            "Accept them by installing at a terminal curl https://testflows.com/machine/install -fsS | bash"
    fi
    # The Agreement is read and accepted at the terminal: a client's sign-in handed over
    # with none has no one to show it to.
    if [ "$SIGNED_IN" = "client" ] && ! ( : < /dev/tty ) 2>/dev/null; then
        die "The Agreement of $version is to be accepted, and there is no terminal to show it at." \
            "Upgrade at a terminal machine upgrade"
    fi
    read_agreement "$version"
    api_call POST /terms/accept "$(json_object version "$version")"
    [ "$API_STATUS" = "204" ] || die "The Agreement was not accepted. $(api_refusal)"
    ok "Accepted the Terms of Service and the Client EULA of $version${ACCOUNT:+ for $ACCOUNT}"
}

# sign_out: end the installer's sign-in, so it leaves no live token behind. An API key is
# the person's own and stays.
sign_out() {
    if [ "$SIGNED_IN" = "access" ]; then
        api_call POST /logout
    fi
    SIGNED_IN=""
    rm -f "${API_HEADERS:-}" "${API_BODY:-}"
    [ -z "$API_NO_CAS" ] || rmdir "$API_NO_CAS" 2>/dev/null || true
    API_NO_CAS=""
}

# release_url PATH: where to download a release file from: a
# link the service signs for the account, valid for minutes. Fails with 1 for a file the
# service has not, 2 when it could not be asked, and 3 when it refused, its words then in
# API_BODY. Run in $(...), so it returns a code where die would end only the subshell.
release_url() {
    api_call GET "/client/releases/$1"
    case "$API_STATUS" in
        200) json_get "$API_BODY" url ;;
        404) return 1 ;;
        401 | 403) return 3 ;;
        *) return 2 ;;
    esac
}

# release_fetch PATH DEST: download a release file, as fetch does; FETCH_STATUS is "final"
# for a file there is not.
release_fetch() {
    local url status=0
    url="$(release_url "$1")" || status=$?
    case "$status" in
        0) fetch "$url" "$2"; return ;;
        1) FETCH_STATUS="final" ;;
        3) die "$(api_refusal)" ;;
        *) FETCH_STATUS="retry" ;;
    esac
    return 1
}

# signed_in_for: an account that may download releases, before the first one is
# downloaded: signed in, and the current Agreement accepted.
signed_in_for() {
    [ "$DOWNLOADER" = "curl" ] || die "Signing in needs curl." "Install curl and run this again."
    choose_helper
    sign_in
    accept_terms
}

# on_exit: remove what the install wrote on the way, and sign out.
on_exit() {
    rm -rf "${TMP:-}" ${TMP:+"$TMP.asc" "$TMP.sig"} "${SUMFILE:-}" ${SUMFILE:+"$SUMFILE.asc" "$SUMFILE.sig"} ${STAGE:+"$STAGE"}
    sign_out
}

# latest_version: the version latest/version names. The installer then downloads
# that version's own files, which never change, so a release published meanwhile
# cannot pair one release's binary with another's checksum.
latest_version() {
    local file version
    file="$(mktemp)" || die "Could not create a temporary file."
    if ! release_fetch latest/version "$file"; then
        rm -f "$file"
        die "Could not download the latest version's name." "Check your connection and try again."
    fi
    version="$(tr -d ' \t\r\n' < "$file")"
    rm -f "$file"
    version_valid "$version" || die "The published latest version isn't valid."
    printf '%s' "$version"
}

# list_versions: print every published version, newest first, and how to install one.
# latest/history holds them oldest first, one a line, and its last line is the latest.
list_versions() {
    local file version latest=""
    file="$(mktemp)" || die "Could not create a temporary file."
    if ! release_fetch latest/history "$file"; then
        rm -f "$file"
        die "Could not download the list of versions." "Check your connection and try again."
    fi
    say "${BOLD}Machine client versions${RESET} ${DIM}(newest first)${RESET}"
    # Reversed with sed, which every system has; tac and tail -r are not on both.
    while IFS= read -r version; do
        version="$(printf '%s' "$version" | tr -d ' \t\r')"
        version_valid "$version" || continue
        if [ -z "$latest" ]; then
            latest="$version"
            say "  $version  ${DIM}latest${RESET}"
        else
            say "  $version"
        fi
    done <<EOF
$(sed '1!G;h;$!d' "$file")
EOF
    rm -f "$file"
    [ -n "$latest" ] || die "No versions are published."
    say ""
    say "Install one:"
    if [ "$SIGNED_IN" = "client" ]; then
        say "  machine upgrade $latest"
    else
        say "  curl https://testflows.com/machine/install -fsS | bash -s -- --version $latest"
    fi
}

# checksum_from FILE: the SHA-256 in a published checksum file. It is a sha256sum
# line ("<hash>  machine") or a bare hash; either way the hash is the first word.
checksum_from() {
    local want
    want="$(tr -d '\r' < "$1" | head -n 1 | tr -s ' \t' ' ' | cut -d ' ' -f 1 | tr 'A-F' 'a-f')"
    case "$want" in
        *[!0-9a-f]* | "") die "The published checksum isn't valid." ;;
    esac
    [ "${#want}" -eq 64 ] || die "The published checksum isn't valid."
    printf '%s' "$want"
}

# Set by --no-signature and --no-checksum; both are said aloud when used.
NO_SIGNATURE=false
NO_CHECKSUM=false
# What the install checked, for the line that reports it.
SIGNED_WITH=""
CHECKSUM_CHECKED=""

# check_signature SUMFILE URL: check the signature on the checksum file downloaded from
# check_signature SUMFILE PATH: check the checksum SUMFILE, the release file PATH, with the
# release keys, before it is trusted. gpg checks PATH.asc; without gpg, openssl checks PATH.sig. A missing or bad signature on an official release stops
# the install: one that could be removed from the server would protect nothing. Sets
# SIGNED_WITH to what checked it, or leaves it empty when nothing could.
check_signature() {
    local sumfile="$1" path="$2" tool sig home ring key
    SIGNED_WITH=""
    if $NO_SIGNATURE; then
        warn "--no-signature: the release signature was not checked."
        return 0
    fi
    if command -v gpg >/dev/null 2>&1; then
        tool="gpg"; sig="$sumfile.asc"
    elif command -v openssl >/dev/null 2>&1; then
        tool="openssl"; sig="$sumfile.sig"
    else
        warn "Neither gpg nor openssl is installed, so the release signature was not checked."
        return 0
    fi
    if ! release_fetch "$path.${sig##*.}" "$sig" 2>/dev/null; then
        rm -f "$sig"
        die "This release's signature could not be downloaded, so it was not installed." \
            "Run this again, and write to contact@testflows.com if it keeps happening."
    fi
    # Each check is an if, not a bare command: under set -e a failing one would end the
    # script before it could say why.
    local verified=false
    if [ "$tool" = "gpg" ]; then
        home="$(mktemp -d)" || die "Could not create a temporary folder."
        chmod 700 "$home"
        ring="$home/release.gpg"
        if printf '%s\n' "$GPG_PUBLIC_KEY" | GNUPGHOME="$home" gpg --batch --quiet --dearmor > "$ring" 2>/dev/null \
            && GNUPGHOME="$home" gpg --batch --quiet --no-default-keyring --keyring "$ring" \
                --verify "$sig" "$sumfile" >/dev/null 2>&1; then
            verified=true
        fi
        rm -rf "$home"
    else
        key="$(mktemp)" || die "Could not create a temporary file."
        printf '%s\n' "$RSA_PUBLIC_KEY" > "$key"
        if openssl dgst -sha256 -verify "$key" -signature "$sig" "$sumfile" >/dev/null 2>&1; then
            verified=true
        fi
        rm -f "$key"
    fi
    rm -f "$sig"
    $verified || die "This release's checksum is not signed by TestFlows, so it was not installed." \
        "Its signature does not match the release key. Write to contact@testflows.com."
    SIGNED_WITH="$tool"
}

# verify_download PATH: check the download TMP against the checksum published as
# PATH.sha256, once that checksum's signature is checked.
verify_download() {
    local path="$1" want got
    release_fetch "$path.sha256" "$SUMFILE" || die "Could not download the checksum for this release." \
        "The install is stopped rather than trusting a file it can't check."
    check_signature "$SUMFILE" "$path.sha256"
    want="$(checksum_from "$SUMFILE")"
    got="$(sha256_of "$TMP")"
    if [ "$got" != "$want" ]; then
        die "The download doesn't match its published checksum, so it was not installed." \
            "expected $want" \
            "got      $got" \
            "Run this again, and write to contact@testflows.com if it keeps happening."
    fi
    CHECKSUM_CHECKED=true
}

# sha256_of FILE: the SHA-256 of a file, in lower case.
sha256_of() {
    if command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$1" | cut -d ' ' -f 1
    elif command -v shasum >/dev/null 2>&1; then
        shasum -a 256 "$1" | cut -d ' ' -f 1
    elif command -v openssl >/dev/null 2>&1; then
        openssl dgst -sha256 "$1" | sed 's/^.*= *//'
    else
        die "Cannot check the download: none of sha256sum, shasum or openssl is installed." \
            "Install one of them and run this again."
    fi
}

# platform_asset: the file each release publishes for this system, and how it installs:
# "binary", one self-extracting file, or "tree", a .tar.gz unpacked into its own folder.
# Sets ASSET, KIND and PLATFORM, its name for messages, and CORE_ASSET, the Python SDK
# core the release publishes for this system; fails for a system no release is built for.
platform_asset() {
    case "$(uname -s)-$(uname -m)" in
        Linux-x86_64 | Linux-amd64)  ASSET="machine";                     KIND="binary"; PLATFORM="Linux x86_64"
                                     CORE_ASSET="_testflows_machine_core.abi3.so" ;;
        Linux-aarch64 | Linux-arm64) ASSET="machine-linux-arm64";         KIND="binary"; PLATFORM="Linux arm64"
                                     CORE_ASSET="_testflows_machine_core-linux-arm64.abi3.so" ;;
        Darwin-arm64)                ASSET="machine-darwin-arm64.tar.gz"; KIND="tree";   PLATFORM="macOS on Apple Silicon"
                                     CORE_ASSET="_testflows_machine_core-darwin-arm64.abi3.so" ;;
        *) return 1 ;;
    esac
}

check_platform() {
    platform_asset && return 0
    local os arch
    os="$(uname -s)"
    arch="$(uname -m)"
    case "$os" in
        Darwin)
            die "The Machine client doesn't run on Intel Macs." \
                "It runs on Macs with Apple Silicon, and on Linux (x86_64 and arm64)." \
                "Need another platform? Write to contact@testflows.com and tell us which."
            ;;
        MINGW* | MSYS* | CYGWIN*)
            die "The Machine client doesn't run on Windows." \
                "Inside WSL, which is Linux, it does." \
                "Need another platform? Write to contact@testflows.com and tell us which."
            ;;
        *)
            die "The Machine client doesn't run on $os $arch." \
                "It runs on Linux (x86_64 and arm64) and on Macs with Apple Silicon." \
                "Need another platform? Write to contact@testflows.com and tell us which."
            ;;
    esac
}

# download_failed RELEASE: say why this platform's file of RELEASE could not be had. A
# release published before this platform was built has files for others only; that is
# told apart from a version never released by its Linux x86_64 checksum, which every
# release has.
download_failed() {
    local release="$1" probe
    if [ "$FETCH_STATUS" = "final" ]; then
        probe="$(mktemp)" || die "Could not create a temporary file."
        if release_fetch "$release/machine.sha256" "$probe" 2>/dev/null; then
            rm -f "$probe"
            if [ -n "${MACHINE_VERSION:-}" ]; then
                die "Version $release has no build for $PLATFORM." \
                    "Install the latest instead: leave MACHINE_VERSION unset."
            fi
            die "The latest release, $release, has no build for $PLATFORM yet." \
                "Write to contact@testflows.com if it doesn't appear soon."
        fi
        rm -f "$probe"
        die "Version $release isn't a released version." \
            "See the versions there are with --list."
    fi
    die "Could not download version $release." "Check your connection and try again."
}

# print_checksum RELEASE: print the published checksum of a release and stop.
print_checksum() {
    local sum
    TMP="$(mktemp)" || die "Could not create a temporary file."
    release_fetch "$1/$ASSET.sha256" "$TMP" || download_failed "$1"
    check_signature "$TMP" "$1/$ASSET.sha256"
    sum="$(checksum_from "$TMP")"
    printf '%s  %s\n' "$sum" "$ASSET"
}

# download_files RELEASE: put this system's file of RELEASE, its checksum and the
# checksum's two signatures in the current folder, for checking by hand with gpg,
# openssl and sha256sum or shasum. Nothing is checked or installed here: the point is to
# check them yourself.
download_files() {
    local release="$1" name
    say "${BOLD}Downloading the Machine client${RESET} ${DIM}($release, $PLATFORM)${RESET}"
    for name in "$ASSET" "$ASSET.sha256" "$ASSET.sha256.asc" "$ASSET.sha256.sig"; do
        FETCH_PROGRESS=false
        [ "$name" = "$ASSET" ] && FETCH_PROGRESS=true
        release_fetch "$release/$name" "$name" || {
            rm -f "$name"
            download_failed "$release"
        }
    done
    ok "Downloaded $ASSET, $ASSET.sha256, $ASSET.sha256.asc and $ASSET.sha256.sig"
    say "  Check them as the Download page shows: https://testflows.com/machine/download/"
}

# The cache folder a machine binary unpacks into: the build key is the second
# 64-byte field of the 152-byte trailer at its end, ahead of the magic TFSFX.
unpack_dir_of() {
    local key magic
    magic="$(tail -c 8 "$1" | head -c 5)"
    [ "$magic" = "TFSFX" ] || return 0
    key="$(tail -c 152 "$1" | head -c 128 | tail -c 64 | tr -d '\0')"
    case "$key" in
        *[!0-9a-f]* | "") return 0 ;;
    esac
    printf '%s/machine/%s' "${XDG_CACHE_HOME:-${HOME:-}/.cache}" "$key"
}

# Remove the folders older versions unpacked into, keeping the current one and any
# a running machine still uses: nothing else removes them.
remove_old_unpacks() {
    local keep="$1" parent dir exe in_use freed=0
    [ -n "$keep" ] || return 0
    parent="$(dirname "$keep")"
    [ -d "$parent" ] || return 0
    for dir in "$parent"/*/; do
        dir="${dir%/}"
        [ -d "$dir" ] && [ "$dir" != "$keep" ] || continue
        case "$(basename "$dir")" in
            *[!0-9a-f]*) continue ;;
        esac
        in_use=false
        for exe in /proc/[0-9]*/exe; do
            case "$(readlink "$exe" 2>/dev/null)" in
                "$dir"/*) in_use=true; break ;;
            esac
        done
        $in_use && continue
        rm -rf "$dir" && freed=$((freed + 1))
    done
    case "$freed" in
        0) ;;
        1) ok "Removed an older version's unpacked files from $(tilde "$parent")" ;;
        *) ok "Removed $freed older versions' unpacked files from $(tilde "$parent")" ;;
    esac
}

# other_machine OURS...: print the first program called machine on PATH that is none of
# OURS, or nothing. `type -ap` lists every match, so an install of ours ahead of it, from a
# PATH line an earlier version of this script printed, does not hide the system's.
other_machine() {
    local found ours skip
    while IFS= read -r found; do
        skip=false
        for ours in "$@"; do
            if [ -e "$ours" ] && [ "$found" -ef "$ours" ]; then
                skip=true
            fi
        done
        # A copy of this client somewhere else on PATH is no other program: taken for
        # one, it moved an ordinary install off PATH. main() names it as a stale copy.
        if ! $skip && [ -n "$(version_of "$found" || true)" ]; then
            skip=true
        fi
        if ! $skip; then
            printf '%s' "$found"
            return 0
        fi
    done < <(type -ap machine 2>/dev/null)
    return 0
}

# retire_machine OLD WHY: remove OLD, a machine this script put where machine no longer
# goes: in the directory on PATH now that machine is kept off it, or the other way round.
# WHY ends the line that says so. Only a file that runs as the client goes: a program of
# someone else's with the name stays where it is. One that cannot be removed is said: it
# is an older client that would otherwise be run without a word.
retire_machine() {
    local old="$1"
    [ -e "$old" ] || [ -L "$old" ] || return 0
    [ -n "$(version_of "$old" || true)" ] || return 0
    if rm -f "$old"; then
        ok "Removed $(tilde "$old"), $2"
    else
        warn "Could not remove $(tilde "$old"), an older copy of the client. Remove it:"
        warn "    rm $(tilde "$old")"
    fi
}

# install_tree RELEASE SHARE TARGET: unpack the verified download TMP into SHARE/RELEASE and
# point TARGET at the executable in it. The tree is unpacked beside its final folder and
# renamed into place, and the link replaced by a rename, so a cut-off install leaves the
# previous one working. Sets INSTALLED to the version the unpacked client reports.
install_tree() {
    local release="$1" share="$2" target="$3" link
    STAGE="$(mktemp -d "$share/.unpack.XXXXXX")" || die "Could not write to $(tilde "$share")."
    tar -xzf "$TMP" -C "$STAGE" || die "The download couldn't be unpacked." \
        "Run this again, and write to contact@testflows.com if it keeps happening."
    INSTALLED="$(version_of "$STAGE/machine/machine" || true)"
    [ -n "$INSTALLED" ] || die "The downloaded client doesn't run on this system." \
        "Write to contact@testflows.com with the output of uname -a and sw_vers."
    rm -rf "${share:?}/$release"
    mv "$STAGE/machine" "$share/$release"
    rmdir "$STAGE"
    STAGE=""
    link="$(mktemp -u "$(dirname "$target")/.machine-link.XXXXXX")"
    ln -s "$share/$release/machine" "$link"
    mv -f "$link" "$target"
}

# tree_in_use DIR: whether a running process executes a file in DIR. lsof lists each
# process's executable by its resolved path, so it finds a client started through the
# link in bin/, whose command line does not name DIR: machine upgrade waits on this
# script from that client. pgrep is the check where there is no lsof.
tree_in_use() {
    local dir="$1"
    if command -v lsof >/dev/null 2>&1; then
        lsof -d txt -Fn 2>/dev/null | grep -qF "n$dir/" && return 0
    fi
    pgrep -f "$dir/machine" > /dev/null 2>&1
}

# remove_old_trees SHARE KEEP: remove the folders older versions were unpacked into, except
# one a running machine uses.
remove_old_trees() {
    local share="$1" keep="$2" dir freed=0
    for dir in "$share"/*/; do
        dir="${dir%/}"
        [ -d "$dir" ] || continue
        version_valid "$(basename "$dir")" || continue
        [ "$(basename "$dir")" = "$keep" ] && continue
        tree_in_use "$dir" && continue
        rm -rf "$dir" && freed=$((freed + 1))
    done
    case "$freed" in
        0) ;;
        1) ok "Removed an older version from $(tilde "$share")" ;;
        *) ok "Removed $freed older versions from $(tilde "$share")" ;;
    esac
}

# install_env DIR: write machine-env into DIR, executable. It is written on every run, so a
# machine installed before machine-env existed gets it on the next one, and it is replaced
# by a rename like the client, so a cut-off write leaves the old one working. machine-env
# finds machine beside itself, or in the data directory where machine is kept off PATH.
install_env() {
    local dir="$1" tmp
    tmp="$(mktemp "$dir/.machine-env.XXXXXX")" || return 1
    cat >"$tmp" <<'END_OF_MACHINE_ENV' || { rm -f "$tmp"; return 1; }
#!/bin/bash
# machine-env: a shell in which `machine` is TestFlows Machine.
#
# macOS ships /usr/bin/machine, which prints the CPU architecture, so a plain
# PATH entry for the client loses to it or shadows it for good. This starts a
# child shell with the client's directory first on PATH. The parent shell is
# never touched: `exit` leaves, and there is nothing to deactivate.
#
# One file for every platform. Where another program is called machine, the
# installer keeps `machine` off PATH, in the data directory, and this is the way
# in. Linux has no /usr/bin/machine, so there `machine` is beside this file and
# this only makes that directory the first match.
#
# Runs on bash 3.2, the bash macOS ships.

set -u

PROMPT_TAG="(machine) "
INSTALL_CMD="curl -fsS https://testflows.com/machine/install | bash"
ONE_COMMAND="machine-env -- machine --version"

usage() {
    cat <<EOF
Usage: machine-env
       machine-env -- command [argument ...]

Starts a shell in which machine is TestFlows Machine, ahead of any other
machine on PATH, and prefixes its prompt with $PROMPT_TAG. The shell loads the
usual configuration first. Tab completes machine's commands and options. Leave
it with exit.

With a command, runs it in that environment and starts no shell.

Supported shells: zsh and bash.
EOF
}

# Verdict first, one hint per line, the shape every machine message has.
refuse() {
    printf '✗ %s\n' "$1" >&2
    shift
    local hint
    for hint in "$@"; do
        printf '  %s\n' "$hint" >&2
    done
    exit 1
}

# The directory `machine` is in: the data directory the installer keeps it in where
# another program is called machine, else beside this script. The data directory
# first: the installer removes the copy it no longer uses, and where it could not,
# the one beside this script is the older client. The script's own directory is not
# resolved through symlinks, so a link names that directory and survives the version
# folder it points into being replaced.
machine_dir() {
    local here kept
    here="$(cd "$(dirname "$0")" && pwd)"
    kept="${XDG_DATA_HOME:-$HOME/.local/share}/machine/bin"
    if [ -x "$kept/machine" ] || [ ! -x "$here/machine" ]; then
        printf '%s' "$kept"
    else
        printf '%s' "$here"
    fi
}

require_machine() {
    [ -x "$1/machine" ] ||
        refuse "No machine in $1" \
            "Reinstall the client $INSTALL_CMD"
}

# Everything that follows the user's own shell setup, as the shell's own syntax.
# PATH is set here and not before the shell starts: a profile that prepends its
# own directories would otherwise put them in front of the client.

start_bash() {
    local tmp="$1" rc="$1/rcfile"
    # An interactive bash that is not a login shell reads ~/.bashrc only. A macOS
    # user whose setup is in ~/.bash_profile would get none of it, so it is the
    # fallback.
    cat >"$rc" <<'EOF'
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
elif [ -f ~/.bash_profile ]; then
    . ~/.bash_profile
fi
PATH="$MACHINE_ENV:$PATH"
export PATH
# Tab completion, from the client now first on PATH: in a startup file, outside
# this shell, machine is macOS's own. A client without completion prints nothing.
eval "$(machine completion bash 2>/dev/null)"
# At every prompt and last, because prompts that rebuild PS1 would drop it.
__machine_env_prompt() {
    case "$PS1" in
    "(machine) "*) ;;
    *) PS1="(machine) $PS1" ;;
    esac
}
PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND;}__machine_env_prompt"
__machine_env_prompt
EOF
    "$SHELL" --rcfile "$rc" -i
}

start_zsh() {
    local tmp="$1"
    # zsh reads its startup files from $ZDOTDIR. Pointing it at a directory of
    # ours is the only way to run after the user's .zshrc, so each file there
    # runs the user's own and puts ZDOTDIR back before the shell reads on.
    MACHINE_ENV_ZDOTDIR="${ZDOTDIR:-$HOME}"
    MACHINE_ENV_ZDOTDIR_UNSET=""
    [ -n "${ZDOTDIR:-}" ] || MACHINE_ENV_ZDOTDIR_UNSET=1
    MACHINE_ENV_TMP="$tmp"
    export MACHINE_ENV_ZDOTDIR MACHINE_ENV_ZDOTDIR_UNSET MACHINE_ENV_TMP
    cat >"$tmp/.zshenv" <<'EOF'
ZDOTDIR="$MACHINE_ENV_ZDOTDIR"
[[ -f $ZDOTDIR/.zshenv ]] && source "$ZDOTDIR/.zshenv"
MACHINE_ENV_ZDOTDIR="$ZDOTDIR"
ZDOTDIR="$MACHINE_ENV_TMP"
EOF
    cat >"$tmp/.zshrc" <<'EOF'
ZDOTDIR="$MACHINE_ENV_ZDOTDIR"
[[ -f $ZDOTDIR/.zshrc ]] && source "$ZDOTDIR/.zshrc"
[[ -n $MACHINE_ENV_ZDOTDIR_UNSET ]] && unset ZDOTDIR
unset MACHINE_ENV_ZDOTDIR MACHINE_ENV_ZDOTDIR_UNSET MACHINE_ENV_TMP
path=("$MACHINE_ENV" $path)
# Tab completion, from the client now first on PATH: in a startup file, outside
# this shell, machine is macOS's own. A client without completion prints nothing.
eval "$(machine completion zsh 2>/dev/null)"
# At every prompt and last, because prompts that rebuild PROMPT would drop it.
__machine_env_prompt() {
    [[ $PROMPT == "(machine) "* ]] || PROMPT="(machine) $PROMPT"
}
precmd_functions+=(__machine_env_prompt)
__machine_env_prompt
EOF
    ZDOTDIR="$tmp" "$SHELL" -i
}

# A shell of the user's, in the environment. A child and not an exec, so the
# directory of startup files is removed when it exits, however it ends: a closed
# terminal hangs this script up, and only a trap runs then. STARTUP_DIR is global
# for the trap to see it.
start_shell() {
    STARTUP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/machine-env.XXXXXX")" ||
        refuse "Cannot create a temporary directory."
    trap 'rm -rf "$STARTUP_DIR"' EXIT
    case "$(basename "$SHELL")" in
    zsh) start_zsh "$STARTUP_DIR" ;;
    bash) start_bash "$STARTUP_DIR" ;;
    esac
    exit $?
}

run_command() {
    [ $# -gt 0 ] || refuse "Command required." "Run one command $ONE_COMMAND"
    PATH="$BIN:$PATH"
    export PATH MACHINE_ENV
    exec "$@"
}

main() {
    case "${1:-}" in
    -h | --help)
        usage
        exit 0
        ;;
    --)
        shift
        BIN="$(machine_dir)"
        require_machine "$BIN"
        MACHINE_ENV="$BIN"
        run_command "$@"
        ;;
    "") ;;
    *) refuse "Unknown argument: $1." "Run one command $ONE_COMMAND" ;;
    esac

    [ -z "${MACHINE_ENV:-}" ] ||
        refuse "Already in the Machine environment." \
            "Leave the environment exit"
    case "$(basename "${SHELL:-}")" in
    zsh | bash) ;;
    *)
        refuse "Unsupported shell: ${SHELL:-not set}." \
            "Run one command $ONE_COMMAND"
        ;;
    esac
    [ -t 0 ] && [ -t 1 ] ||
        refuse "Not a terminal." "Run one command $ONE_COMMAND"

    BIN="$(machine_dir)"
    require_machine "$BIN"
    MACHINE_ENV="$BIN"
    export MACHINE_ENV
    start_shell
}

# Everything runs in main, called last: a cut-off copy executes nothing.
main "$@"
END_OF_MACHINE_ENV
    chmod 755 "$tmp" && mv -f "$tmp" "$dir/machine-env" || { rm -f "$tmp"; return 1; }
}

# path_line DIR: the line that puts DIR on PATH, for the shell this user runs.
path_line() {
    local dir="$1" shown
    shown="$(tilde "$dir")"
    [ "$shown" != "$dir" ] && shown="\$HOME${shown#\~}"
    case "$(basename "${SHELL:-}")" in
        bash) say "    echo 'export PATH=\"$shown:\$PATH\"' >> ~/.bashrc" ;;
        zsh)  say "    echo 'export PATH=\"$shown:\$PATH\"' >> ~/.zshrc" ;;
        fish) say "    fish_add_path \"$shown\"" ;;
        *)    say "  Add this line to your shell's startup file:"
              say "    export PATH=\"$shown:\$PATH\"" ;;
    esac
}

# path_file: the startup file of the shell this user runs, or nothing for a shell whose
# file this script does not write.
path_file() {
    case "$(basename "${SHELL:-}")" in
        bash) printf '%s' "$HOME/.bashrc" ;;
        zsh)  printf '%s' "${ZDOTDIR:-$HOME}/.zshrc" ;;
    esac
}

# path_add DIR: put DIR on PATH in the startup file of the user's shell, when the user
# says so. Returns 0 when the file has the line, 1 when it does not and the line is still
# the user's to add. Asked at the terminal and never assumed: the file is the user's. The
# script itself is on standard input under `curl | bash`, so the answer is read from the
# terminal, and with no terminal, as in CI, nothing is asked and nothing written.
# MACHINE_NO_MODIFY_PATH set to anything asks nothing.
path_add() {
    local dir="$1" file shown line answer
    [ -z "${MACHINE_NO_MODIFY_PATH:-}" ] || return 1
    file="$(path_file)"
    [ -n "$file" ] || return 1
    shown="$(tilde "$dir")"
    [ "$shown" != "$dir" ] && shown="\$HOME${shown#\~}"
    line="export PATH=\"$shown:\$PATH\""
    # There from an earlier run, in a shell started before it was.
    if [ -f "$file" ] && grep -qF "$line" "$file"; then
        ok "$(tilde "$file") puts $(tilde "$dir") on your PATH. Open a new terminal."
        return 0
    fi
    ( : < /dev/tty ) 2>/dev/null || return 1
    printf '  Add it to your PATH in %s? [y/N] ' "$(tilde "$file")" > /dev/tty
    IFS= read -r answer < /dev/tty || return 1
    case "$answer" in
        y | Y | yes | Yes | YES) ;;
        *) return 1 ;;
    esac
    printf '\n# TestFlows Machine\n%s\n' "$line" >> "$file" || {
        warn "Could not write $(tilde "$file")."
        return 1
    }
    ok "Added $(tilde "$dir") to your PATH in $(tilde "$file"). Open a new terminal."
}

# path_hint DIR: DIR holds machine and is not on PATH, so the shell cannot find it.
path_hint() {
    say ""
    warn "$(tilde "$1") is not on your PATH, so your shell can't find machine yet."
    path_add "$1" && return 0
    say "  Run this, then open a new terminal:"
    say ""
    path_line "$1"
}

# next_in_env DIR OTHER: what to do next when OTHER, another program called machine, is
# on PATH. machine is kept off PATH then, so it hides nothing, and DIR holds machine-env
# alone. machine-env starts a shell in which machine is this client and marks its prompt,
# so the steps are shown as they will look in that shell.
# The line that turns Tab completion on in the user's shell, for its startup file.
# Not where machine-env is the way in: it loads completion itself, and outside it
# machine is another program, which the line would run in every new shell.
completion_hint() {
    local line
    case "$(basename "${SHELL:-}")" in
    bash) line="echo 'eval \"\$(machine completion bash)\"' >> ~/.bashrc" ;;
    zsh) line="echo 'eval \"\$(machine completion zsh)\"' >> ~/.zshrc" ;;
    fish) line="echo 'machine completion fish | source' >> ~/.config/fish/config.fish" ;;
    *) return 0 ;;
    esac
    say ""
    say "Tab completion, in terminals opened after this:"
    say "  $line"
}

next_in_env() {
    local dir="$1" other="$2" env="machine-env" on_path=true
    # Not on PATH, machine-env is found no more than machine is: name it in full.
    case ":$PATH:" in
        *":$dir:"*) ;;
        *) on_path=false; env="$(tilde "$dir/machine-env")" ;;
    esac
    say ""
    warn "Another program called machine is on your PATH: $(tilde "$other")"
    say "  machine is kept off your PATH, so it does not hide that one."
    say "  Use machine-env, a shell where machine is this client and Tab completes it."
    say ""
    say "Next:"
    say "  \$ $env"
    say "  (machine) \$ machine login    sign in (or  machine account signup  to create an account)"
    say "  (machine) \$ machine --help   see every command"
    say "  (machine) \$ exit             leave it, back to the shell you were in"
    $on_path && return 0
    say ""
    warn "$(tilde "$dir") is not on your PATH, so machine-env is typed with its path."
    say "  It holds machine-env alone, so putting it on your PATH hides nothing."
    path_add "$dir" && return 0
    say "  Run this, then open a new terminal:"
    say ""
    path_line "$dir"
}

# The Python SDK core: the one file the SDK loads, licensed and published as the client
# is, one for each system the client is built for. It is installed under one name on
# every system, in the client's own folder, where the SDK looks for it, with the release
# it came from beside it.
CORE_FILE="_testflows_machine_core.abi3.so"
CORE_DIR_NAME=".testflows/machine/sdk"

# install_core RELEASE: put RELEASE's Python SDK core in place, as the client is: downloaded
# signed in, its checksum and signature checked, then renamed into place. Skipped where
# it is that release's already, and for a release from before the core shipped. A
# download that fails leaves the client installed and says so.
install_core() {
    local release="$1" dir version
    dir="$HOME/$CORE_DIR_NAME"
    version="$(cat "$dir/version" 2>/dev/null || true)"
    if [ "$version" = "$release" ] && [ -s "$dir/$CORE_FILE" ]; then
        return 0
    fi
    mkdir -p "$dir" || { warn "Could not create $(tilde "$dir"); the Python SDK core was not installed."; return 0; }
    TMP="$(mktemp "$dir/.core.XXXXXX")" || { warn "Could not write to $(tilde "$dir")."; return 0; }
    SUMFILE="$TMP.sha256"
    # Quiet: a release from before the core answers 404, which is said below.
    FETCH_QUIET=true
    if ! release_fetch "$release/$CORE_ASSET" "$TMP"; then
        FETCH_QUIET=false
        if [ "$FETCH_STATUS" = "final" ]; then
            say "  ${DIM}Release $release has no Python SDK core.${RESET}"
        else
            warn "Could not download the Python SDK core. Run this again to install it."
        fi
        rm -f "$TMP" "$SUMFILE"
        TMP=""
        SUMFILE=""
        return 0
    fi
    FETCH_QUIET=false
    if $NO_CHECKSUM; then
        warn "--no-checksum: the Python SDK core's checksum and signature were not checked."
    else
        verify_download "$release/$CORE_ASSET"
    fi
    mv -f "$TMP" "$dir/$CORE_FILE" || die "Could not install $(tilde "$dir/$CORE_FILE")."
    printf '%s\n' "$release" > "$dir/version" || warn "Could not write $(tilde "$dir/version")."
    rm -f "$SUMFILE"
    TMP=""
    SUMFILE=""
    ok "Installed the Python SDK core to $(tilde "$dir/$CORE_FILE")"
}

# up_to_date VERSION TARGET: the latest is installed already; say so, and how to
# install it again.
up_to_date() {
    ok "machine $1 is the latest, and is installed at $(tilde "$2")"
    if [ "$SIGNED_IN" = "client" ]; then
        say "  Reinstall ${BOLD}machine upgrade $1${RESET}"
    else
        say "  Reinstall ${BOLD}curl https://testflows.com/machine/install -fsS | bash -s -- --version $1${RESET}"
    fi
}

main() {
    local mode="install" arg
    while [ $# -gt 0 ]; do
        arg="$1"
        shift
        case "$arg" in
            --list) mode="list" ;;
            --version)
                [ $# -gt 0 ] || die "--version needs a version." "See them with --list."
                MACHINE_VERSION="$1"
                shift
                ;;
            --version=*) MACHINE_VERSION="${arg#--version=}" ;;
            --checksum) mode="checksum" ;;
            --download) mode="download" ;;
            --no-signature) NO_SIGNATURE=true ;;
            --no-checksum) NO_CHECKSUM=true; NO_SIGNATURE=true ;;
            -h | --help) usage; exit 0 ;;
            *) die "Unknown option: $arg" "Run it with --help to see what it accepts." ;;
        esac
    done

    trap on_exit EXIT

    # A list is the same on every system, so it is answered before the platform check.
    if [ "$mode" = "list" ]; then
        choose_downloader
        signed_in_for
        list_versions
        return 0
    fi

    # Before any download: on a system it doesn't run on, say so, not a network error.
    # --checksum runs anywhere, for checking a file by hand; off a supported system it
    # prints the Linux x86_64 file's. --download fetches this system's files.
    if [ "$mode" = "checksum" ]; then
        platform_asset || { ASSET="machine"; KIND="binary"; PLATFORM="Linux x86_64"; }
    else
        check_platform
    fi
    choose_downloader
    [ "$PROTOCOLS" = "=https" ] || warn "Downloading over plain HTTP from $BASE_URL, as TESTFLOWS_MACHINE_API_URL asks."

    signed_in_for

    local release
    if [ -n "${MACHINE_VERSION:-}" ]; then
        version_valid "$MACHINE_VERSION" \
            || die "'$MACHINE_VERSION' is not a version." "A version looks like YYYYMMDD-HHMM." \
                "See the versions there are with --list."
        release="$MACHINE_VERSION"
    else
        release="$(latest_version)"
    fi

    if [ "$mode" = "checksum" ]; then
        print_checksum "$release"
        return 0
    fi
    if [ "$mode" = "download" ]; then
        download_files "$release"
        return 0
    fi

    # The client keeps its sign-in and unpacks itself under HOME, so it needs one.
    [ -n "${HOME:-}" ] || die "HOME is not set." "The client needs a home directory to run."
    local dir="${MACHINE_INSTALL_DIR:-$HOME/.local/bin}"
    local share="${XDG_DATA_HOME:-$HOME/.local/share}/machine"
    local path="$release/$ASSET"

    # Where another program is called machine, as /usr/bin/machine is on a Mac, machine goes
    # to a directory that is not on PATH, so no PATH line can hide that program. DIR then
    # holds machine-env alone, which is the way in and is safe to put on PATH.
    local other bin
    other="$(other_machine "$dir/machine" "$share/bin/machine")"
    bin="$dir"
    [ -z "$other" ] || bin="$share/bin"
    local target="$bin/machine"

    # An install from before machine was kept off PATH has it in DIR, so DIR is read second.
    local before="" candidate
    for candidate in "$target" "$dir/machine"; do
        [ -x "$candidate" ] || continue
        before="$(version_of "$candidate" || true)"
        [ -z "$before" ] || break
    done

    # The latest, installed already, is not downloaded again. A version named is
    # installed whatever is there, which is how an install is repaired.
    if [ -z "${MACHINE_VERSION:-}" ] && [ "$before" = "$release" ]; then
        up_to_date "$release" "$target"
        install_core "$release"
        return 0
    fi

    say "${BOLD}Installing the Machine client${RESET} ${DIM}($release)${RESET}"
    mkdir -p "$dir" || die "Could not create $(tilde "$dir")."
    mkdir -p "$bin" || die "Could not create $(tilde "$bin")."

    # Download next to where it ends up, so the last step is a rename. TMP, SUMFILE and
    # STAGE are global so on_exit can still see them when die() exits from here.
    local downloads="$bin"
    if [ "$KIND" = "tree" ]; then
        downloads="$share"
        mkdir -p "$share" || die "Could not create $(tilde "$share")."
    fi
    TMP="$(mktemp "$downloads/.machine.XXXXXX")" || die "Could not write to $(tilde "$downloads")."
    SUMFILE="$TMP.sha256"
    STAGE=""

    FETCH_PROGRESS=true
    release_fetch "$path" "$TMP" || download_failed "$release"
    FETCH_PROGRESS=false
    [ -s "$TMP" ] || die "The download was empty."

    if $NO_CHECKSUM; then
        warn "--no-checksum: neither the checksum nor the signature was checked."
    else
        verify_download "$path"
    fi

    local after
    if [ "$KIND" = "tree" ]; then
        install_tree "$release" "$share" "$target"
        after="$INSTALLED"
    else
        chmod +x "$TMP"
        after="$(version_of "$TMP" || true)"
        [ -n "$after" ] || die "The downloaded file doesn't run on this system." \
            "Write to contact@testflows.com with the output of uname -a."
        mv -f "$TMP" "$target"
    fi
    rm -f "$SUMFILE"
    TMP=""
    SUMFILE=""
    STAGE=""

    local env_written=true
    install_env "$dir" || env_written=false

    # machine is in one place: the copy an earlier run put in the other one goes, or
    # machine-env and a PATH line would find an older client there.
    if [ "$bin" = "$dir" ]; then
        retire_machine "$share/bin/machine" "from when another program was called machine"
    else
        retire_machine "$dir/machine" "which would hide $(tilde "$other")"
    fi

    if [ -z "$before" ]; then
        ok "Installed machine $after to $(tilde "$target")${CHECKSUM_CHECKED:+ ${DIM}(${SIGNED_WITH:+signed and }checksum verified)${RESET}}"
    elif [ "$before" = "$after" ]; then
        ok "machine $after was already installed. Reinstalled it at $(tilde "$target")"
    else
        ok "Updated machine $before → $after at $(tilde "$target")"
    fi
    # Where machine-env is, said as machine's place is: it is the one to type where
    # another program is called machine, and nothing else names its directory.
    if $env_written; then
        ok "Installed machine-env to $(tilde "$dir/machine-env")"
    else
        warn "Could not write $(tilde "$dir/machine-env")."
    fi
    install_core "$release"

    if [ "$KIND" = "tree" ]; then
        remove_old_trees "$share" "$release"
    else
        remove_old_unpacks "$(unpack_dir_of "$target")"
    fi

    # A machine is x86_64: on an ARM system, Docker's default arm64 images cannot be disks.
    if [ "$ASSET" != "machine" ]; then
        say ""
        warn "This is an ARM system, and a machine runs x86_64. Build disks from"
        warn "linux/amd64 images: docker build or docker pull with --platform linux/amd64."
        say "  ${DIM}https://testflows.com/docs/machine/#building-disks-on-an-arm-machine${RESET}"
    fi

    # With no other program called machine, typing `machine` must find the one just
    # installed. With one, machine is off PATH and machine-env is the way in.
    if [ -n "$other" ]; then
        next_in_env "$dir" "$other"
    else
        local found
        found="$(command -v machine 2>/dev/null || true)"
        if [ -z "$found" ]; then
            path_hint "$dir"
        elif ! [ "$found" -ef "$target" ]; then
            # A copy of the client that other_machine did not count as another program.
            say ""
            warn "An older copy of the client comes first on your PATH: $(tilde "$found")"
            say "  Typing machine runs that one. Remove it:"
            say ""
            say "    rm $(tilde "$found")"
        fi
        # An upgrade's client is signed in and knows its commands already.
        if [ "$SIGNED_IN" != "client" ]; then
            say ""
            say "Next:"
            say "  machine login         sign in (or  machine account signup  to create an account)"
            say "  machine --help        see every command"
            completion_hint
        fi
    fi
    say ""
    say "Docs: https://testflows.com/docs/machine/"
}

main "$@"
