#!/bin/sh
# SPDX-License-Identifier: LicenseRef-ShakerProxy-Proprietary
# Copyright (c) 2026 ShakerProxy. All rights reserved. See LICENSE.

# ShakerProxy one-line installer: what https://get.<domain>/install serves.
#
#   curl -fsSL https://get.<domain>/install | sudo sh          (asks for the code)
#   curl -fsSL https://get.<domain>/install | sudo sh -s -- --code SPX-XXXX-…
#   curl -fsSL https://get.<domain>/install | sh -s -- --download-only ./shakerproxy-offline
#
# It holds no product and no secret. With your access code it asks the
# ShakerProxy download service for your license and the current release,
# verifies the release signature against ShakerProxy's pinned release key and
# the license with the release's own license checker BEFORE the large
# download, downloads the release (resumably, every file checked against the
# signed manifest) and runs the release's own tested installer
# (install.sh --offline-bundle). It then installs the license and keeps the
# access code (root only, /etc/shakerproxy/access-code) for the updates you
# run later: `sudo shakerproxy update`, `sudo shakerproxy license refresh`.
#
# ShakerProxy never contacts the download service on its own; only this
# installer, `shakerproxy update` and `shakerproxy license refresh` do, when a
# person runs them. What they send: docs/what-shakerproxy-sends.md (or run
# with --dry-run, which prints every request it makes).
#
# Options:
#   --code SPX-…            your access code (without it the installer asks, and does not echo it)
#   --license FILE          install this license file instead of the one the service holds
#   --download-only DIR     download and verify everything into DIR for a box without internet;
#                           any Linux or macOS machine, no sudo needed
#   --version 1.2.3         this release instead of the newest one
#   --channel stable|beta   follow this channel (default: the access code's)
#   --dry-run               check this machine, the code, the license and the release, printing every
#                           request; downloads only the small signed manifest and license checker
#                           (into a temporary directory) and changes nothing
#   --update                update an installed box (what `sudo shakerproxy update` runs); uses the
#                           stored access code unless --code is given
#   --check                 with --update: say what is available; download nothing
#   -- ARGS                 pass ARGS to the release installer (install.sh), e.g. -- --profile standard

# Everything runs inside main(), so a partly downloaded script does nothing.
main() {
    set -eu
    umask 077

    # Written by packaging/render-get-installer.sh from
    # packaging/download-service.conf; the placeholder never resolves.
    DOWNLOAD_HOST="get.shakerscan.com"
    # ShakerProxy's release signing key (packaging/release-public.pem).
    TRUSTED_RELEASE_KEY_SHA256="e8c3c965ed4859f55e69af55ccb03d20d297843104b611f0a754072694dafdcb"
    BOOTSTRAP_VERSION="1"

    # Tests point these at a local fake service and a scratch root.
    SERVICE="${SHAKERPROXY_DOWNLOAD_URL:-https://$DOWNLOAD_HOST}"
    SERVICE="${SERVICE%/}"
    ROOT="${SHAKERPROXY_TEST_ROOT:-}"

    CODE="${SHAKERPROXY_ACCESS_CODE:-}"
    LICENSE_FILE=""
    DOWNLOAD_ONLY=""
    WANT_VERSION=""
    CHANNEL=""
    DRY_RUN=0
    UPDATE=0
    CHECK=0
    CODE_GIVEN=0
    CODE_IN_ARGUMENTS=0
    WORK=""
    PRIVATE=""
    INSTALLER_ARGS_FILE=""
    trap cleanup EXIT
    trap 'exit 130' INT TERM

    PRIVATE="$(mktemp -d "${TMPDIR:-/tmp}/shakerproxy-get.XXXXXX")"
    INSTALLER_ARGS_FILE="$PRIVATE/installer-args"
    : > "$INSTALLER_ARGS_FILE"
    while [ $# -gt 0 ]; do
        case "$1" in
            --code) need_value "$@"; CODE="$2"; CODE_GIVEN=1; CODE_IN_ARGUMENTS=1; shift 2 ;;
            --code=*) CODE="${1#--code=}"; CODE_GIVEN=1; CODE_IN_ARGUMENTS=1; shift ;;
            --license|--license-file) need_value "$@"; LICENSE_FILE="$2"; shift 2 ;;
            --download-only) need_value "$@"; DOWNLOAD_ONLY="$2"; shift 2 ;;
            --version) need_value "$@"; WANT_VERSION="${2#v}"; shift 2 ;;
            --channel) need_value "$@"; CHANNEL="$2"; shift 2 ;;
            --dry-run) DRY_RUN=1; shift ;;
            --update) UPDATE=1; shift ;;
            --check) CHECK=1; shift ;;
            -h|--help) usage; return 0 ;;
            --) shift; for argument in "$@"; do printf '%s\n' "$argument" >> "$INSTALLER_ARGS_FILE"; done; break ;;
            *) fail "unknown option: $1" "Run with --help for the options." ;;
        esac
    done
    validate_options

    say "ShakerProxy installer"
    check_machine
    ensure_tools
    read_code
    INSTALLED_VERSION="$(installed_version)"

    entitlement
    if [ "$UPDATE" = 1 ] && [ -n "$INSTALLED_VERSION" ] && { [ "$INSTALLED_VERSION" = "$RELEASE_VERSION" ] || newer "$INSTALLED_VERSION" "$RELEASE_VERSION"; } && [ -z "$WANT_VERSION" ]; then
        say "ShakerProxy $INSTALLED_VERSION is installed and up to date (the newest $RELEASE_CHANNEL release for $ORG is $RELEASE_VERSION). Nothing to do."
        [ "$CODE_GIVEN" = 0 ] || [ "$DRY_RUN" = 1 ] || store_access_code
        return 0
    fi
    if [ "$CHECK" = 1 ]; then
        say "Available: ShakerProxy $RELEASE_VERSION ($RELEASE_CHANNEL)${INSTALLED_VERSION:+; installed: $INSTALLED_VERSION}. Nothing was downloaded."
        say "Install it with: sudo shakerproxy update"
        return 0
    fi

    # The signed manifest is checked in the private temporary directory
    # before any directory is made from the release it names.
    verify_release
    prepare_work_dir
    verify_license
    if [ "$DRY_RUN" = 1 ]; then
        say ""
        say "Dry run finished: the access code, the license and the signed release check out."
        say "Only the signed manifest and the license checker were downloaded, into a temporary directory that is now deleted. Nothing was installed or changed."
        return 0
    fi
    check_disk
    download_release
    if [ -n "$DOWNLOAD_ONLY" ]; then
        finish_download_only
        return 0
    fi
    run_installer
    store_access_code
    rm -rf -- "$WORK"
    WORK=""
    finish_install
}

say() { printf '%s\n' "$*"; }
step_line() { printf '  %-30s %s\n' "$1" "$2"; }
fail() {
    printf '\nError: %s\n' "$1" >&2
    [ $# -lt 2 ] || printf '%s\n' "$2" >&2
    exit 1
}
have() { command -v "$1" >/dev/null 2>&1; }
# valid_version succeeds when the whole value is a release version: one
# line, only these characters, so it is safe as a directory and URL part.
valid_version() {
    case "$1" in ""|*[!0-9A-Za-z.-]*) return 1 ;; esac
    printf '%s\n' "$1" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$'
}
need_value() { [ $# -ge 2 ] && [ -n "$2" ] || fail "$1 needs a value."; }

usage() {
    cat <<EOF
Usage: curl -fsSL https://$DOWNLOAD_HOST/install | sudo sh -s -- [options]

  --code SPX-…            your access code; without it the installer asks and does not echo it
                          (on the command line, other users can see it while it runs, and sudo logs it)
  --license FILE          install this license file instead of the one the service holds
  --download-only DIR     download and verify everything into DIR for a box without internet
                          (any Linux or macOS machine, no sudo needed)
  --version 1.2.3         this release instead of the newest one
  --channel stable|beta   follow this channel (default: the access code's)
  --dry-run               check this machine, the code, the license and the release, printing every
                          request; downloads only the small signed manifest and license checker
                          (into a temporary directory) and changes nothing
  --update [--check]      update an installed box (sudo shakerproxy update runs this)
  -- ARGS                 pass ARGS to the release installer, e.g. -- --profile standard
EOF
}

cleanup() {
    [ -z "${PRIVATE:-}" ] || rm -rf -- "$PRIVATE"
}

validate_options() {
    case "$CHANNEL" in
        ""|stable|beta|nightly) ;;
        *) fail "--channel must be stable, beta or nightly, not '$CHANNEL'." ;;
    esac
    if [ -n "$WANT_VERSION" ] && ! valid_version "$WANT_VERSION"; then
        fail "--version must look like 1.2.3, not '$WANT_VERSION'."
    fi
    [ "$CHECK" = 0 ] || [ "$UPDATE" = 1 ] || fail "--check goes with --update (sudo shakerproxy update --check)."
    [ -z "$DOWNLOAD_ONLY" ] || [ "$UPDATE" = 0 ] || fail "--download-only and --update do not go together."
    if [ -n "$LICENSE_FILE" ]; then
        [ -f "$LICENSE_FILE" ] && [ -r "$LICENSE_FILE" ] || fail "cannot read the license file $LICENSE_FILE."
    fi
    case "$SERVICE" in
        https://*) CURL_PROTO="=https" ;;
        http://127.0.0.1:*|http://localhost:*)
            # Tests only: a local fake service, exactly http://HOST:PORT.
            port="${SERVICE##*:}"
            case "$port" in ""|*[!0-9]*) fail "the download service must be an https:// address." ;; esac
            [ "$SERVICE" = "http://127.0.0.1:$port" ] || [ "$SERVICE" = "http://localhost:$port" ] || fail "the download service must be an https:// address."
            CURL_PROTO="=http,https"
            ;;
        *) fail "the download service must be an https:// address." ;;
    esac
    case "$DOWNLOAD_HOST$SERVICE" in
        *.invalid*)
            [ -n "${SHAKERPROXY_DOWNLOAD_URL:-}" ] || fail "the ShakerProxy download service is not set up yet, so nothing can be fetched online." \
                "Ask your ShakerProxy contact for the release files and a license file, then: sudo bash <dir>/install.sh --offline-bundle <dir> --license <dir>/license.spl"
            ;;
    esac
}

check_machine() {
    OS="$(uname -s)"
    ARCH="$(uname -m)"
    case "$ARCH" in
        x86_64|amd64) ARCH=amd64 ;;
        aarch64|arm64) ARCH=arm64 ;;
    esac
    case "$OS" in
        Linux) PLATFORM="linux-$ARCH" ;;
        Darwin) PLATFORM="darwin-$ARCH" ;;
        *) PLATFORM="" ;;
    esac
    if [ -n "$DOWNLOAD_ONLY" ]; then
        [ -n "$PLATFORM" ] || fail "--download-only runs on Linux or macOS, not $OS."
        step_line "This machine" "ok ($OS $ARCH; downloading for a box elsewhere)"
        return 0
    fi
    [ "$OS" = Linux ] || fail "ShakerProxy installs on Ubuntu Linux, not $OS." \
        "To download for a box elsewhere, add --download-only <directory>."
    [ "$ARCH" = amd64 ] || fail "ShakerProxy supports amd64 (x86_64) machines; this one is $(uname -m)."
    [ -r "$ROOT/etc/os-release" ] || fail "cannot tell which Linux this is (/etc/os-release is missing)."
    # A subshell: os-release defines VERSION, NAME and more.
    # shellcheck disable=SC1091
    os_release="$(. "$ROOT/etc/os-release" && printf '%s:%s' "${ID:-}" "${VERSION_ID:-}")"
    case "$os_release" in
        ubuntu:24.04|ubuntu:26.04) ;;
        *) fail "ShakerProxy supports Ubuntu Server 24.04 and 26.04; this is ${os_release:-an unknown system}." ;;
    esac
    if [ -f "$ROOT/.dockerenv" ] || [ -f "$ROOT/run/.containerenv" ]; then
        fail "this is a container. Install ShakerProxy on the machine itself: it manages the machine's network ports."
    fi
    have systemctl || fail "ShakerProxy needs systemd, which this machine is not running."
    if [ "$DRY_RUN" = 0 ] && [ "$(id -u)" -ne 0 ]; then
        fail "installing ShakerProxy needs root, because it manages this machine's network." \
            "Run it with sudo: curl -fsSL https://$DOWNLOAD_HOST/install | sudo sh"
    fi
    step_line "This machine" "ok (Ubuntu ${os_release#ubuntu:}, amd64)"
}

ensure_tools() {
    missing=""
    for tool in curl jq openssl; do have "$tool" || missing="$missing $tool"; done
    have sha256sum || have shasum || missing="$missing sha256sum"
    [ -n "$missing" ] || return 0
    if [ -z "$DOWNLOAD_ONLY" ] && [ "$(id -u)" -eq 0 ] && have apt-get; then
        say "  Installing:$missing"
        apt-get -o DPkg::Lock::Timeout=600 update -qq >/dev/null
        DEBIAN_FRONTEND=noninteractive apt-get install -y -qq -o DPkg::Lock::Timeout=600 ca-certificates coreutils curl jq openssl >/dev/null
        return 0
    fi
    fail "this needs:$missing." "Install them (macOS: brew install jq), then run the command again."
}

sha256_of() {
    if have sha256sum; then sha256sum "$1" | awk '{print $1}'; else shasum -a 256 "$1" | awk '{print $1}'; fi
}

read_code() {
    if [ -z "$CODE" ] && [ "$UPDATE" = 1 ] && [ -r "$ROOT/etc/shakerproxy/access-code" ]; then
        CODE="$(cat "$ROOT/etc/shakerproxy/access-code")"
    fi
    if [ -z "$CODE" ]; then
        if ! { : </dev/tty; } 2>/dev/null; then
            fail "no access code was given." "Add --code SPX-… (from your ShakerProxy email), for example: curl -fsSL https://$DOWNLOAD_HOST/install | sudo sh -s -- --code SPX-…"
        fi
        printf 'ShakerProxy access code: ' >/dev/tty
        stty -echo </dev/tty 2>/dev/null || true
        IFS= read -r CODE </dev/tty || CODE=""
        stty echo </dev/tty 2>/dev/null || true
        printf '\n' >/dev/tty
        CODE_GIVEN=1
    fi
    CODE="$(printf '%s' "$CODE" | tr -d ' \t\r\n' | tr '[:lower:]' '[:upper:]')"
    printf '%s\n' "$CODE" | grep -Eq '^SPX-[0-9A-Z]{4}(-[0-9A-HJKMNP-TV-Z]{4}){5}$' \
        || fail "this is not a ShakerProxy access code (it looks like SPX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX)." "Copy it from your ShakerProxy email."
    if [ "$CODE_IN_ARGUMENTS" = 1 ]; then
        printf '%s\n' "Note: an access code given with --code is on this command's command line while it runs, where other users of this machine can see it (ps), and sudo writes it to its log. Leave out --code and the installer asks for it instead." >&2
    fi
    # The code goes to curl in a private file, never on curl's command line
    # or in a URL, so curl shows it in no process list and no server log.
    AUTH="$PRIVATE/auth.conf"
    printf 'header = "Authorization: Bearer %s"\n' "$CODE" > "$AUTH"
}

installed_version() {
    target="$(readlink "$ROOT/opt/shakerproxy/current" 2>/dev/null || true)"
    [ -z "$target" ] || basename "$target"
}

# newer A B succeeds when release A is newer than release B; 1.2.3 is newer
# than its prerelease 1.2.3-beta.9.
newer() {
    [ "$1" != "$2" ] || return 1
    newer_core="${1%%-*}"
    older_core="${2%%-*}"
    if [ "$newer_core" = "$older_core" ]; then
        [ "$1" != "$newer_core" ] || return 0
        [ "$2" != "$older_core" ] || return 1
    else
        set -- "$newer_core" "$older_core"
    fi
    [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n 1)" = "$1" ]
}

# refusal STATUS FILE prints the service's refusal in the words every
# ShakerProxy command uses (internal/distribution Explain).
refusal() {
    error="$(jq -r '.error // ""' "$2" 2>/dev/null || true)"
    org="$(jq -r '.org // ""' "$2" 2>/dev/null || true)"
    ends="$(jq -r '.access_until // ""' "$2" 2>/dev/null || true)"
    unchanged="Your installed ShakerProxy is unchanged."
    if [ "$UPDATE" = 1 ]; then
        action="sudo shakerproxy update"
        with_code="sudo shakerproxy update --code SPX-…"
    else
        action="curl -fsSL https://$DOWNLOAD_HOST/install | sudo sh"
        with_code="curl -fsSL https://$DOWNLOAD_HOST/install | sudo sh -s -- --code SPX-…"
    fi
    message="$(jq -r '.message // ""' "$2" 2>/dev/null | tr -cd '\040-\176' | cut -c1-400 || true)"
    # The download gate (deploy/download-worker) names some refusals its own way.
    case "$error" in
        expired_code) error=code_expired ;;
        revoked_code) error=code_revoked ;;
        too_many_attempts|too_many_requests) error=rate_limited ;;
    esac
    case "$error" in
        code_expired) printf 'Access for %s ended%s. %s Ask for a renewal, then run `%s`.\n' "${org:-this access code}" "${ends:+ on $ends}" "$unchanged" "$action" ;;
        code_revoked) printf 'This access code was turned off (it was replaced or revoked). %s Use the newest code from your ShakerProxy email: `%s`.\n' "$unchanged" "$with_code" ;;
        unknown_code) printf 'The download service does not know this access code. %s Check it against your ShakerProxy email: it looks like SPX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX.\n' "$unchanged" ;;
        no_release) printf 'No release is available for this access code on that channel. %s\n' "$unchanged" ;;
        rate_limited) printf 'Too many wrong access codes were tried from this network. %s Wait a minute and try again.\n' "$unchanged" ;;
        *)
            # Any other refusal carries the service's own message.
            if [ -n "$message" ]; then
                case "$message" in
                    *unchanged*|*Unchanged*) printf '%s\n' "$message" ;;
                    *) printf '%s %s\n' "$message" "$unchanged" ;;
                esac
                return 0
            fi
            case "$1" in
                401|403) printf 'The download service refused the access code. %s Ask your ShakerProxy contact for a renewal.\n' "$unchanged" ;;
                429) printf 'The download service is busy. %s Wait a minute and try again.\n' "$unchanged" ;;
                000) printf 'The download service at %s could not be reached. %s Check this machine'"'"'s internet access and DNS.\n' "$SERVICE" "$unchanged" ;;
                *) printf 'The download service answered HTTP %s. %s Try again later.\n' "$1" "$unchanged" ;;
            esac
            ;;
    esac
}

entitlement() {
    client=install
    [ "$UPDATE" = 0 ] || client=update
    # `shakerproxy update` hands over the box's signed request code (as
    # `license refresh` sends it), so a renewal comes back bound to this box.
    request_code=""
    if [ "$UPDATE" = 1 ]; then
        request_code="${SHAKERPROXY_REQUEST_CODE:-}"
        case "$request_code" in
            SPR1.?*) ;;
            *) request_code="" ;;
        esac
        # Only base64url and dots, one line, bounded.
        if [ "${#request_code}" -gt 8192 ] || [ "$(printf '%s#' "$request_code" | LC_ALL=C tr -d 'A-Za-z0-9_.-')" != "#" ]; then
            request_code=""
        fi
    fi
    jq -n --arg client "$client" --arg version "$INSTALLED_VERSION" --arg channel "$CHANNEL" --arg want "$WANT_VERSION" --arg request "$request_code" \
        '{client:$client} + (if $version != "" then {version:$version} else {} end)
         + (if $channel != "" then {channel:$channel} else {} end) + (if $want != "" then {want:$want} else {} end)
         + (if $request != "" then {request_code:$request} else {} end)' > "$PRIVATE/request.json"
    if [ "$DRY_RUN" = 1 ]; then
        say ""
        say "  Every request to the download service, as it is made (the access code goes only in the"
        say "  Authorization header of each one):"
        say "    POST $SERVICE/v1/entitlement"
        say "    Authorization: Bearer <your access code>"
        say "    $(jq -c . "$PRIVATE/request.json")"
    fi
    status="$(curl --proto "$CURL_PROTO" --tlsv1.2 -sS --connect-timeout 20 --max-time 60 -K "$AUTH" \
        -H 'Content-Type: application/json' -H "User-Agent: shakerproxy-installer/$BOOTSTRAP_VERSION" \
        --data-binary "@$PRIVATE/request.json" -o "$PRIVATE/entitlement.json" -w '%{http_code}' "$SERVICE/v1/entitlement" 2>/dev/null)" || status="${status:-000}"
    if [ "$status" != 200 ]; then
        [ -f "$PRIVATE/entitlement.json" ] || : > "$PRIVATE/entitlement.json"
        fail "$(refusal "$status" "$PRIVATE/entitlement.json")"
    fi
    jq -e '(.org | type == "string") and (.license_id | type == "string") and (.release.version | type == "string") and (.release.channel | type == "string")' "$PRIVATE/entitlement.json" >/dev/null 2>&1 \
        || fail "the download service sent an answer this installer cannot read." "Your installed ShakerProxy is unchanged. Try again later."
    ORG="$(jq -r '.org' "$PRIVATE/entitlement.json")"
    LICENSE_ID="$(jq -r '.license_id' "$PRIVATE/entitlement.json")"
    ACCESS_UNTIL="$(jq -r '.access_until // ""' "$PRIVATE/entitlement.json")"
    RELEASE_VERSION="$(jq -r '.release.version' "$PRIVATE/entitlement.json")"
    RELEASE_CHANNEL="$(jq -r '.release.channel' "$PRIVATE/entitlement.json")"
    valid_version "$RELEASE_VERSION" || fail "the download service named an invalid release."
    case "$RELEASE_CHANNEL" in stable|beta|nightly) ;; *) fail "the download service named an invalid channel." ;; esac
    [ -z "$WANT_VERSION" ] || [ "$WANT_VERSION" = "$RELEASE_VERSION" ] || fail "the download service offers $RELEASE_VERSION, not $WANT_VERSION." "Your installed ShakerProxy is unchanged."
    [ -z "$CHANNEL" ] || [ "$CHANNEL" = "$RELEASE_CHANNEL" ] || fail "the download service offers a $RELEASE_CHANNEL release, not $CHANNEL." "Your installed ShakerProxy is unchanged."
    [ "$DRY_RUN" = 0 ] || say ""
    step_line "Access code" "ok ($ORG${ACCESS_UNTIL:+, downloads until $ACCESS_UNTIL})"
}

prepare_work_dir() {
    if [ "$DRY_RUN" = 1 ]; then
        WORK="$PRIVATE/release"
        mkdir -p "$WORK"
    elif [ -n "$DOWNLOAD_ONLY" ]; then
        WORK="$DOWNLOAD_ONLY"
        mkdir -p "$WORK"
        WORK="$(cd "$WORK" && pwd -P)"
        chmod 0755 "$WORK"
    else
        # Not /tmp: a reboot or tmp cleaner must not take a half-finished
        # download, and the next run resumes it.
        WORK="$ROOT/var/lib/shakerproxy/downloads/$RELEASE_VERSION"
        mkdir -p "$WORK"
        chmod 0700 "$WORK"
    fi
    for name in manifest.json manifest.json.sig release-public.pem; do
        cp -- "$PRIVATE/signed/$name" "$WORK/$name"
    done
}

# fetch DIR NAME [SHA256] [BYTES] downloads one release file into DIR,
# resuming a partial file; with SHA256 a file already complete is kept as it
# is. BYTES is the most it may be: the signed manifest's size, or a small cap
# for the files read before the manifest is verified.
fetch() {
    directory="$1"
    name="$2"
    expected="${3:-}"
    limit="${4:-}"
    case "$name" in
        *[!A-Za-z0-9._-]*|.*) fail "the signed release names an unexpected file: $name" ;;
    esac
    case "$limit" in
        "") limit_option="" ;;
        *[!0-9]*) fail "the signed release gives $name an invalid size." ;;
        *) limit_option="--max-filesize $limit" ;;
    esac
    destination="$directory/$name"
    if [ -n "$expected" ] && [ -f "$destination" ] && [ "$(sha256_of "$destination")" = "$expected" ]; then
        return 0
    fi
    [ "$DRY_RUN" = 0 ] || say "    GET $SERVICE/v1/files/$RELEASE_VERSION/$name"
    attempt=1
    while :; do
        set +e
        # shellcheck disable=SC2086 # limit_option is empty or two words
        curl --proto "$CURL_PROTO" --tlsv1.2 -sS --fail --connect-timeout 20 --speed-limit 1024 --speed-time 60 -K "$AUTH" $limit_option \
            -H "User-Agent: shakerproxy-installer/$BOOTSTRAP_VERSION" -C - -o "$destination" \
            "$SERVICE/v1/files/$RELEASE_VERSION/$name" 2>"$PRIVATE/curl.err"
        result=$?
        set -e
        # Never more than the release says, however the service answers.
        if [ -n "$limit" ] && [ -f "$destination" ] && [ "$(wc -c < "$destination" | tr -d ' ')" -gt "$limit" ]; then
            rm -f -- "$destination"
            result=63
        fi
        if [ "$result" = 63 ]; then
            rm -f -- "$destination"
            fail "the download service sent more for $name than the release holds ($limit bytes); nothing was installed." "Run the command again; if it keeps failing, tell your ShakerProxy contact."
        fi
        if [ "$result" = 0 ]; then
            if [ -z "$expected" ] || [ "$(sha256_of "$destination")" = "$expected" ]; then
                return 0
            fi
            # A complete file that does not match: start it again once.
            rm -f -- "$destination"
        elif grep -q 'The requested URL returned error: 416' "$PRIVATE/curl.err" 2>/dev/null; then
            # Nothing left to resume, yet it did not match: start again.
            rm -f -- "$destination"
        elif grep -Eq 'returned error: (401|403|404|429)' "$PRIVATE/curl.err" 2>/dev/null; then
            code="$(sed -nE 's/.*returned error: ([0-9]+).*/\1/p' "$PRIVATE/curl.err" | head -n 1)"
            # Ask once without the file, to read why.
            [ "$DRY_RUN" = 0 ] || say "    POST $SERVICE/v1/entitlement (again, to read why $name was refused)"
            curl --proto "$CURL_PROTO" --tlsv1.2 -sS --connect-timeout 20 --max-time 60 --max-filesize 65536 -K "$AUTH" -o "$PRIVATE/refusal.json" \
                -H 'Content-Type: application/json' --data-binary "@$PRIVATE/request.json" "$SERVICE/v1/entitlement" >/dev/null 2>&1 || true
            [ -f "$PRIVATE/refusal.json" ] || : > "$PRIVATE/refusal.json"
            jq -e '.error' "$PRIVATE/refusal.json" >/dev/null 2>&1 || printf '{}' > "$PRIVATE/refusal.json"
            fail "$(refusal "$code" "$PRIVATE/refusal.json")" "The files downloaded so far are kept in $directory; run the command again to resume."
        fi
        attempt=$((attempt + 1))
        if [ "$attempt" -gt 6 ]; then
            fail "could not download $name: $(tr '\n' ' ' < "$PRIVATE/curl.err")" \
                "Check this machine's internet access and run the same command again: the download resumes where it stopped. Your installed ShakerProxy is unchanged."
        fi
        sleep "$attempt"
    done
}

# manifest_size KEY prints the signed manifest's size of that artifact (a
# jq path such as .host_package), or nothing for a release without sizes.
manifest_size() {
    jq -r "($1.size // \"\") | tostring" "$WORK/manifest.json"
}

# verify_release checks the signed manifest in the private temporary
# directory: nothing outside it is made or changed until it verifies.
verify_release() {
    signed="$PRIVATE/signed"
    mkdir -p "$signed"
    for name in manifest.json manifest.json.sig release-public.pem; do
        fetch "$signed" "$name" "" 1048576
    done
    actual_key="$(openssl pkey -pubin -in "$signed/release-public.pem" -outform DER 2>/dev/null | openssl dgst -sha256 | awk '{print $NF}')"
    [ "$actual_key" = "$TRUSTED_RELEASE_KEY_SHA256" ] || fail "the release key is not ShakerProxy's pinned release key; nothing was installed."
    openssl dgst -sha256 -verify "$signed/release-public.pem" -signature "$signed/manifest.json.sig" "$signed/manifest.json" >/dev/null 2>&1 \
        || fail "the release signature does not verify; nothing was installed." "Run the command again; if it keeps failing, tell your ShakerProxy contact."
    jq -e --arg key "$TRUSTED_RELEASE_KEY_SHA256" --arg version "$RELEASE_VERSION" --arg channel "$RELEASE_CHANNEL" '
        def sha256: type == "string" and test("^[a-f0-9]{64}$");
        def artifact: (.sha256 | sha256) and ((has("size") | not) or (.size | type == "number" and . >= 1 and floor == .));
        .schema == 1 and .version == $version and .channel == $channel and .release_public_key_sha256 == $key and
        (.installer | artifact) and (.host_package | artifact) and (.compose_bundle | artifact) and
        ((has("image_archive") | not) or (.image_archive | artifact)) and
        ((has("license_check") | not) or (.license_check | type == "object" and all(.[]; artifact)))
    ' "$signed/manifest.json" >/dev/null 2>&1 || fail "the signed release manifest is not the release the download service named ($RELEASE_VERSION, $RELEASE_CHANNEL)."
    step_line "Release" "$RELEASE_VERSION (signature ok)"
}

verify_license() {
    if [ -n "$LICENSE_FILE" ]; then
        cp -- "$LICENSE_FILE" "$PRIVATE/license.spl"
    else
        jq -r '.license_token // ""' "$PRIVATE/entitlement.json" > "$PRIVATE/license.spl"
    fi
    grep -q '^v4\.public\.' "$PRIVATE/license.spl" || fail "the download service holds no license for this access code." \
        "Ask your ShakerProxy contact for the license file, then add --license <file>. Your installed ShakerProxy is unchanged."
    chmod 0644 "$PRIVATE/license.spl"
    if ! jq -e 'has("license_check")' "$WORK/manifest.json" >/dev/null 2>&1; then
        step_line "License" "$LICENSE_ID for $ORG (checked when it is installed: this release has no license checker)"
        return 0
    fi
    checker=""
    if [ -n "$PLATFORM" ] && jq -e --arg p "$PLATFORM" '.license_check[$p]' "$WORK/manifest.json" >/dev/null 2>&1; then
        checker="shakerproxy-license-check-$PLATFORM"
        fetch "$WORK" "$checker" "$(jq -r --arg p "$PLATFORM" '.license_check[$p].sha256' "$WORK/manifest.json")" "$(manifest_size ".license_check[\"$PLATFORM\"]")"
        chmod 0755 "$WORK/$checker"
    fi
    if [ -z "$checker" ]; then
        step_line "License" "$LICENSE_ID for $ORG (checked on the box: no license checker for $PLATFORM)"
        return 0
    fi
    set +e
    "$WORK/$checker" verify --json "$PRIVATE/license.spl" > "$PRIVATE/license-check.json" 2>"$PRIVATE/license-check.err"
    result=$?
    set -e
    case "$result" in
        0)
            step_line "License" "$(jq -r '"\(.org), \(.license_id), valid until \(.expires_at)"' "$PRIVATE/license-check.json")"
            ;;
        3)
            step_line "License" "not checked (this release trusts no license keys and enforces none)"
            ;;
        *)
            message="$(jq -r '.message // ""' "$PRIVATE/license-check.json" 2>/dev/null || true)"
            fix="$(jq -r '.fix // ""' "$PRIVATE/license-check.json" 2>/dev/null || true)"
            [ -n "$message" ] || message="$(cat "$PRIVATE/license-check.err")"
            fail "the license does not work with ShakerProxy $RELEASE_VERSION: $message" "${fix:+$fix }Nothing was downloaded and your installed ShakerProxy is unchanged."
            ;;
    esac
}

check_disk() {
    [ -z "$DOWNLOAD_ONLY" ] || return 0
    minimum="$(jq -r '.minimum.disk_gib // 0' "$WORK/manifest.json")"
    # An update downloads and loads only the new images.
    if [ -n "$INSTALLED_VERSION" ]; then minimum=5; fi
    available="$(df -Pk "$ROOT/var/lib" 2>/dev/null | awk 'NR == 2 { print int($4 / 1048576) }')"
    if [ -n "$available" ] && [ "$minimum" -gt 0 ] 2>/dev/null && [ "$available" -lt "$minimum" ]; then
        fail "only $available GiB are free under /var/lib; ShakerProxy needs at least $minimum GiB." "Free space there (or grow the disk), then run the command again."
    fi
}

# release_files prints NAME SHA256 SIZE for each release file ("-" when the
# release names no size).
release_files() {
    jq -r '
        def line($name): "\($name) \(.sha256) \(.size // "-")";
        (.installer | line("install.sh")),
        (.host_package | line("shakerproxy-host.deb")),
        (.compose_bundle | line("compose-bundle.tar.zst")),
        (if has("image_archive") then (.image_archive | line("images.tar.zst")) else empty end),
        # The box checks its license with the Linux checker, wherever the
        # files were downloaded.
        (if has("license_check") and .license_check["linux-amd64"] then (.license_check["linux-amd64"] | line("shakerproxy-license-check-linux-amd64")) else empty end)
    ' "$WORK/manifest.json"
}

download_release() {
    release_files > "$PRIVATE/files"
    count="$(wc -l < "$PRIVATE/files" | tr -d ' ')"
    printf '  %-30s %s\n' "Downloading $count files" "(resumes if interrupted)"
    while read -r name sha256 size; do
        [ "$size" != - ] || size=""
        fetch "$WORK" "$name" "$sha256" "$size" < /dev/null
    done < "$PRIVATE/files"
    while read -r name sha256 _; do
        [ "$(sha256_of "$WORK/$name")" = "$sha256" ] || fail "$name does not match the signed manifest." "Run the command again to download it again."
    done < "$PRIVATE/files"
    chmod 0755 "$WORK/install.sh"
    [ ! -f "$WORK/shakerproxy-license-check-linux-amd64" ] || chmod 0755 "$WORK/shakerproxy-license-check-linux-amd64"
    install -m 0644 "$PRIVATE/license.spl" "$WORK/license.spl"
    step_line "Downloaded" "ok (every file matches the signed manifest)"
}

finish_download_only() {
    for name in shakerproxy-license-check-darwin-arm64 shakerproxy-license-check-darwin-amd64 shakerproxy-license-check-linux-arm64; do
        [ "$name" = "shakerproxy-license-check-linux-amd64" ] || rm -f -- "$WORK/$name"
    done
    if has_license_checker; then
        install_commands="  sudo bash <directory>/install.sh --offline-bundle <directory> --license <directory>/license.spl"
    else
        # A release without a license checker cannot take --license.
        install_commands="  sudo bash <directory>/install.sh --offline-bundle <directory>
  sudo shakerproxy license install <directory>/license.spl"
    fi
    cat > "$WORK/README.txt" <<EOF
ShakerProxy $RELEASE_VERSION ($RELEASE_CHANNEL) for $ORG, license $LICENSE_ID.

Every file here was checked against the release's signed manifest, and the
license against the release's own license checker. Copy this whole
directory to the box (Ubuntu Server 24.04 or 26.04, amd64), then run:

$install_commands

<directory> must be an absolute path, for example /media/usb/shakerproxy-offline.
Nothing here contacts the internet; the box needs no access to it.
EOF
    chmod 0644 "$WORK/README.txt"
    say ""
    say "Downloaded ShakerProxy $RELEASE_VERSION for $ORG to $WORK."
    say "Copy that directory to the box, then run there:"
    say "$install_commands"
}

# has_license_checker succeeds when the release has its own license
# checker, so its install.sh takes --license.
has_license_checker() {
    jq -e 'has("license_check")' "$WORK/manifest.json" >/dev/null 2>&1
}

run_installer() {
    say "  Installing ..."
    set -- --offline-bundle "$WORK" --channel "$RELEASE_CHANNEL" --version "$RELEASE_VERSION"
    # A release without a license checker (one from before it) refuses
    # --license; its license goes in after the install instead.
    if has_license_checker; then set -- "$@" --license "$WORK/license.spl"; fi
    while IFS= read -r argument; do
        set -- "$@" "$argument"
    done < "$INSTALLER_ARGS_FILE"
    # stdin is this script when piped from curl; the installer must not read it.
    env "SHAKERPROXY_ALLOW_ADMIN=${SHAKERPROXY_ALLOW_ADMIN:-}" "SSH_CONNECTION=${SSH_CONNECTION:-}" bash "$WORK/install.sh" "$@" < /dev/null \
        || fail "the installer stopped (see above). The download is kept in $WORK; run the same command again to retry without downloading again."
    has_license_checker && return 0
    shakerproxy license install "$WORK/license.spl" \
        || fail "ShakerProxy $RELEASE_VERSION is installed, but its license was not (see above)." "The license is kept in $WORK/license.spl; install it with: sudo shakerproxy license install $WORK/license.spl"
}

# store_access_code keeps the code for the updates a person runs later
# (`sudo shakerproxy update`, `sudo shakerproxy license refresh`): root only.
store_access_code() {
    directory="$ROOT/etc/shakerproxy"
    mkdir -p "$directory"
    temporary="$directory/.access-code.$$"
    (umask 077 && printf '%s\n' "$CODE" > "$temporary")
    chmod 0600 "$temporary"
    [ -n "$ROOT" ] || chown root:root "$temporary" 2>/dev/null || true
    mv -f -- "$temporary" "$directory/access-code"
}

finish_install() {
    say ""
    say "ShakerProxy $RELEASE_VERSION is licensed to $ORG ($LICENSE_ID)."
    say "  Status:  shakerproxy license"
    say "  Update:  sudo shakerproxy update      (only runs when you run it)"
    say "ShakerProxy never contacts us on its own: see docs/what-shakerproxy-sends.md."
}

main "$@"
