#!/bin/sh
# Installs the `kite` CLI, or kite-control with `control`.
#
#   curl -fsSL https://get.kiteplane.dev | sh
#   curl -fsSL https://get.kiteplane.dev/control | sh
#
# Requires sh and curl, on amd64 or arm64. get.kiteplane.dev serves this file
# at every path except /control, where it serves control.sh: this file with
# `control` as the default mode. scripts/make-build.ts writes control.sh.
#
# The CLI installs on macOS or Linux, to ~/.local/bin, without root.
#
# kite-control installs on a Linux host with systemd. The script downloads and
# checks the release as the current user. It then puts kite-control, and the
# node agent that kite-control serves, in /opt/kite/control/<version>/, using
# sudo unless it runs as root. Last, it runs `kite-control install`, which sets
# up the service (bins/kite-server/src/install.rs).
#
# Environment:
#   KITE_CHANNEL         release channel: stable (default) or edge
#   KITE_VERSION         install this version instead of the channel's
#   KITE_INSTALL_DIR     where to install the CLI (default ~/.local/bin)
#   KITE_ADDRESS         https://<name>[:<port>], where your machine and your
#                        nodes reach kite-control. A first install listens on
#                        that port, with a certificate for that name. Without
#                        it, kite-control listens on 443 for the host's name.
#   KITE_INSTALL_VERIFY  how to check the signature: openssl, node or none
#   KITE_RELEASES        releases host (default https://releases.kiteplane.dev)
#   KITE_RELEASE_KEY     signing key to trust instead of the built-in one,
#                        for tests
#   KITE_INSTALL_ROOT    install kite-control under this directory instead of
#                        /, and leave its files owned by the current user, for
#                        tests
#   KITE_RELEASE_DIR     take release KITE_VERSION from this directory, with
#                        its manifest in `manifest`, instead of the releases
#                        host: `kite deploy --source` copies it there
#
# The script checks the signature on release.json with OpenSSL 3 if it is
# installed, or Node.js if not. It then checks each file's size and SHA-256
# against the signed manifest before it replaces anything. A release stores
# each binary gzipped, as `<file>.gz`, and the script unpacks it after the
# check. Older releases store binaries uncompressed.
#
# Without OpenSSL 3 or Node.js, the CLI installs with its signature unchecked,
# and the script says so. The installed CLI checks the signature of every
# release it deploys. Nothing checks kite-control after it is installed, so
# the script refuses to install it unchecked unless KITE_INSTALL_VERIFY=none.
#
# bins/kite/src/deploy/build.rs defines the release layout.
# docs/decisions/2026-11-19-sign-each-releases-manifest-and-check-every-file-against-it.md
# gives the reason for the signature.

set -eu

# The release signing key. It must match the key in
# bins/kite/src/deploy/build.rs, and scripts/install.test.ts checks that it
# does.
PUBLISHER_KEY="Jl+3PDBmpcytY/ZDAL/weYz0hpwtIpuiXew6kEwIJNQ="

# scripts/make-build.ts builds control.sh by changing `cli` to `control` on the
# next line. Keep the line exactly as it is, or the build fails.
what="${1:-cli}"
releases="${KITE_RELEASES:-https://releases.kiteplane.dev}"
channel="${KITE_CHANNEL:-stable}"
version="${KITE_VERSION:-}"
key="${KITE_RELEASE_KEY:-$PUBLISHER_KEY}"
root="${KITE_INSTALL_ROOT:-}"
from_dir="${KITE_RELEASE_DIR:-}"

fail() {
  printf 'kite install: %s\n' "$*" >&2
  exit 1
}

download_url() {
  for attempt in 1 2 3; do
    if http=$(curl -fsSL -o "$2" -w '%{http_code}' "$1"); then
      return 0
    else
      code=$?
    fi
    case "$code:$http" in
      22:404) fail "${3:-could not download $1.}" ;;
      22:408|22:429|22:500|22:502|22:503|22:504) ;;
      # DNS, connection, HTTP/2, partial transfer, timeout, empty reply, send or receive failure.
      6:*|7:*|16:*|18:*|28:*|52:*|55:*|56:*|92:*) ;;
      *) break ;;
    esac
    if [ "$attempt" -lt 3 ]; then sleep "$attempt"; fi
  done
  fail "could not download $1."
}

case "$what" in
  cli) thing="kite CLI" systems="macOS and Linux" ;;
  control) thing=kite-control systems=Linux ;;
  *) fail "unknown mode '$what'. Run with no argument for the kite CLI, or with 'control' for kite-control." ;;
esac
case "$what-$(uname -s)" in
  cli-Darwin) os=darwin ;;
  *-Linux) os=linux ;;
  *) fail "no $thing is built for $(uname -s). It is built for $systems." ;;
esac
case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  arm64 | aarch64) arch=arm64 ;;
  *) fail "no $thing is built for $(uname -m). It is built for amd64 and arm64." ;;
esac
# Prefix for commands that write outside the download directory: sudo, or
# nothing when the script runs as root.
as_root=""
if [ "$what" = control ]; then
  command -v systemctl >/dev/null 2>&1 \
    || fail "kite-control runs as a systemd service, but this host has no systemctl."
  # kite-control links glibc dynamically, built against 2.28. A host with musl,
  # or an older glibc, would fail to start it after the install.
  glibc="$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{ print $2 }')"
  major="${glibc%%.*}" minor="${glibc#*.}"
  minor="${minor%%.*}"
  case "$major.$minor" in
    *[!0-9.]* | .* | *.) fail "kite-control needs glibc 2.28 or later, and this host has no glibc." ;;
  esac
  [ "$major" -gt 2 ] || { [ "$major" -eq 2 ] && [ "$minor" -ge 28 ]; } \
    || fail "kite-control needs glibc 2.28 or later, and this host has glibc $glibc."
  if [ "$(id -u)" != 0 ]; then
    command -v sudo >/dev/null 2>&1 \
      || fail "kite-control installs as root, but this host has no sudo. Run this script as root."
    # Check sudo before downloading anything. Run a command rather than
    # `sudo -v`: `sudo -v` prompts for a password if any sudoers rule for the user
    # requires one, and the default user on a cloud image has no password.
    sudo true || fail "kite-control installs as root, and sudo refused."
    as_root=sudo
  fi
fi

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

if [ -z "$version" ]; then
  download_url "$releases/channels/$channel" "$tmp/channel" \
    "no channel '$channel' at $releases. The channels are stable and edge: set KITE_CHANNEL=edge for the newest build of main."
  version="$(tr -d '[:space:]' < "$tmp/channel")"
fi
case "$version" in
  "" | *[!0-9A-Za-z.-]*) fail "'$version' is not a valid release version." ;;
esac

if [ -n "$from_dir" ]; then
  # A release that `kite deploy --source` built and copied here over the
  # host's own connection. Nothing signs it. Its manifest lists each file's
  # SHA-256 and size, which `download` checks as it does for a published
  # release.
  cp "$from_dir/manifest" "$tmp/manifest" || fail "$from_dir has no manifest."
else
  download_url "$releases/releases/$version/release.json" "$tmp/release.json"

  # release.json is one line of JSON with two base64 strings.
  field() {
    sed -n "s/.*\"$1\":\"\([A-Za-z0-9+/=]*\)\".*/\1/p" "$tmp/release.json"
  }
  manifest="$(field manifest)"
  signature="$(field signature)"
  [ -n "$manifest" ] && [ -n "$signature" ] \
    || fail "release $version's release.json is not a signed manifest."
  printf '%s' "$manifest" | base64 --decode >"$tmp/manifest" \
    || fail "release $version's manifest is not base64."
  printf '%s' "$signature" | base64 --decode >"$tmp/signature" \
    || fail "release $version's signature is not base64."

  # An Ed25519 public key as SubjectPublicKeyInfo DER: this prefix, then the
  # 32 raw bytes of the key.
  {
    printf '\060\052\060\005\006\003\053\145\160\003\041\000'
    printf '%s' "$key" | base64 --decode
  } >"$tmp/key.der" || fail "the publisher key is not base64."

  # OpenSSL supports Ed25519 from 3.0. The LibreSSL that ships with macOS does
  # not.
  openssl3() {
    case "$(openssl version 2>/dev/null)" in
      "OpenSSL "[3-9]*) return 0 ;;
    esac
    return 1
  }

  verifier="${KITE_INSTALL_VERIFY:-}"
  if [ -z "$verifier" ]; then
    if openssl3; then
      verifier=openssl
    elif command -v node >/dev/null 2>&1; then
      verifier=node
    elif [ "$what" = cli ]; then
      verifier=none
    else
      fail "install OpenSSL 3 or Node.js to check the signature of release $version, or set KITE_INSTALL_VERIFY=none to install kite-control unchecked."
    fi
  fi
  unsigned="release $version's release.json is not signed by Kite's publisher. Nothing was installed."
  case "$verifier" in
    openssl)
      openssl3 \
        || fail "KITE_INSTALL_VERIFY=openssl requires OpenSSL 3 or later for Ed25519, but found $(openssl version 2>/dev/null || echo 'no openssl')."
      openssl pkeyutl -verify -pubin -keyform DER -inkey "$tmp/key.der" -rawin \
        -in "$tmp/manifest" -sigfile "$tmp/signature" >/dev/null 2>&1 || fail "$unsigned"
      ;;
    node)
      node -e '
        const { createPublicKey, verify } = require("node:crypto");
        const { readFileSync } = require("node:fs");
        const [key, manifest, signature] = process.argv.slice(1);
        const pub = createPublicKey({ key: readFileSync(key), format: "der", type: "spki" });
        process.exit(verify(null, readFileSync(manifest), pub, readFileSync(signature)) ? 0 : 1);
      ' "$tmp/key.der" "$tmp/manifest" "$tmp/signature" || fail "$unsigned"
      ;;
    none)
      printf 'kite install: the signature of release %s is not checked: install OpenSSL 3 or Node.js to check it.\n' "$version" >&2
      ;;
    *) fail "KITE_INSTALL_VERIFY must be openssl, node or none, not '$verifier'." ;;
  esac
fi

grep -q '"product":"kite"' "$tmp/manifest" || fail "release $version is not a Kite release."
grep -q "\"version\":\"$version\"" "$tmp/manifest" \
  || fail "release $version's manifest is signed for a different version."

# Prints the manifest's `files` entry for $1: a flat object with its name,
# SHA-256 and size. Prints nothing if the release has no such file.
entry() {
  grep -o '{[^{}]*}' "$tmp/manifest" | grep -F "\"name\":\"$1\"" || true
}

# Succeeds if the release has the file $1, gzipped or not.
has_file() {
  [ -n "$(entry "$1.gz")" ] || [ -n "$(entry "$1")" ]
}

# Downloads the release's file $1 to $2 and checks it against the signed
# manifest. If the release has $1.gz, downloads and checks that instead, then
# unpacks it to $2.
fetch() {
  if [ -n "$(entry "$1.gz")" ]; then
    command -v gzip >/dev/null 2>&1 || fail "gzip is required to unpack $1.gz. Install gzip."
    download "$1.gz" "$2.gz"
    gzip -dc "$2.gz" >"$2" || fail "$1.gz is not gzip. Nothing was installed."
    rm -f "$2.gz"
  else
    download "$1" "$2"
  fi
}

# Downloads the release's file $1 to $2 and fails unless its size and SHA-256
# match the signed manifest.
download() {
  want="$(entry "$1" | sed -n 's/.*"sha256":"\([0-9a-f]*\)".*/\1/p')"
  size="$(entry "$1" | sed -n 's/.*"size":\([0-9]*\).*/\1/p')"
  [ -n "$want" ] && [ -n "$size" ] || fail "release $version has no file $1."
  if [ -n "$from_dir" ]; then
    cp "$from_dir/$1" "$2" || fail "$from_dir has no $1."
  else
    download_url "$releases/releases/$version/$1" "$2"
  fi
  if command -v sha256sum >/dev/null 2>&1; then
    got="$(sha256sum "$2" | awk '{ print $1 }')"
  else
    got="$(shasum -a 256 "$2" | awk '{ print $1 }')"
  fi
  bytes="$(wc -c <"$2" | tr -d '[:space:]')"
  [ "$got" = "$want" ] && [ "$bytes" = "$size" ] \
    || fail "$1 does not match its SHA-256 and size in the signed manifest. Nothing was installed."
}

install_cli() {
  file="kite-$os-$arch"
  dir="${KITE_INSTALL_DIR:-$HOME/.local/bin}"
  has_file "$file" \
    || fail "release $version has no kite CLI for $os-$arch. Set KITE_CHANNEL or KITE_VERSION to install another release."
  fetch "$file" "$tmp/kite"
  mkdir -p "$dir"
  chmod 755 "$tmp/kite"
  # Rename into place, so a running `kite` keeps the file it started from.
  mv -f "$tmp/kite" "$dir/kite"
  printf 'installed %s\n' "$("$dir/kite" version)"
  case ":$PATH:" in
    *":$dir:"*) ;;
    *) printf 'add %s to your PATH to run kite\n' "$dir" ;;
  esac
}

install_control() {
  file="kite-control-linux-$arch"
  has_file "$file" \
    || fail "release $version has no kite-control for linux-$arch. Set KITE_CHANNEL or KITE_VERSION to install another release."
  new="$tmp/new"
  mkdir -p "$new/agent"
  fetch "$file" "$new/kite-control"
  # The node agent that kite-control serves, in the layout KITE_AGENT_DIR
  # expects: bundle.json, plus each binary at the asset path listed in
  # bundle.json. A release stores each asset as `asset-` followed by its path
  # with / replaced by - (assetFile in scripts/make-build.ts). `fetch` adds the
  # `.gz`.
  fetch asset-bundle.json "$new/agent/bundle.json"
  # shellcheck disable=SC2013 # an asset path contains no spaces
  for asset in $(grep -o '"asset":"[^"]*"' "$new/agent/bundle.json" | sed 's/^"asset":"//; s/"$//'); do
    mkdir -p "$new/agent/$(dirname "$asset")"
    fetch "asset-$(printf '%s' "$asset" | tr / -)" "$new/agent/$asset"
  done
  chmod 755 "$new/kite-control"
  # The service runs as its own user, which must be able to read these files
  # whatever root's umask is.
  chmod -R a+rX "$new"

  # Stage the version's directory next to its final path, then rename it, so
  # the directory is either complete or absent.
  opt="$root/opt/kite/control"
  $as_root mkdir -p "$opt"
  $as_root rm -rf "${opt:?}/.$version"
  $as_root mv "$new" "$opt/.$version"
  rooted "$opt/.$version"
  $as_root rm -rf "${opt:?}/$version"
  $as_root mv "$opt/.$version" "$opt/$version"
  # Pass KITE_ADDRESS as an argument, because sudo does not pass the
  # environment through. A kite-control too old to support `install` or
  # `install --address` exits with status 2, its usage error.
  status=0
  if [ -n "${KITE_ADDRESS:-}" ]; then
    $as_root "$opt/$version/kite-control" install --address "$KITE_ADDRESS" || status=$?
  else
    $as_root "$opt/$version/kite-control" install || status=$?
  fi
  [ "$status" != 2 ] \
    || fail "release $version's kite-control is too old for this installer. Set KITE_CHANNEL or KITE_VERSION to install a later release."
  return "$status"
}

# Makes root the owner of files written as another user. Under
# KITE_INSTALL_ROOT nothing runs as root, so ownership is left alone.
rooted() {
  [ -n "$root" ] || $as_root chown -R 0:0 "$@"
}

case "$what" in
  cli) install_cli ;;
  control) install_control ;;
esac
