#!/bin/sh
# Install the kite CLI from a published build.
#
#   curl -fsSL https://get.kiteplane.dev | sh
#
# scripts/publish-build.ts puts this file at the root of the releases address
# where edge moves, and get.kiteplane.dev serves it at every path. It runs on a
# person's machine, macOS or Linux, amd64 or arm64, with sh and curl and
# nothing from a checkout. No root: it writes to a directory the person owns.
#
# KITE_CHANNEL names the channel to follow, stable by default. KITE_INSTALL_DIR
# is where `kite` goes, ~/.local/bin by default. KITE_RELEASES replaces the
# address, which a test points at a server of its own.
#
# The binary is checked against the build's SHA256SUMS before it replaces
# anything, so a download that went wrong is refused rather than installed.

set -eu

releases="${KITE_RELEASES:-https://releases.kiteplane.dev}"
channel="${KITE_CHANNEL:-stable}"
dir="${KITE_INSTALL_DIR:-$HOME/.local/bin}"

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

case "$(uname -s)" in
  Darwin) os=darwin ;;
  Linux) os=linux ;;
  *) fail "no kite CLI is built for $(uname -s). It is built for macOS and Linux." ;;
esac
case "$(uname -m)" in
  x86_64 | amd64) arch=amd64 ;;
  arm64 | aarch64) arch=arm64 ;;
  *) fail "no kite CLI is built for $(uname -m). It is built for amd64 and arm64." ;;
esac
file="kite-$os-$arch"

sha="$(curl -fsSL "$releases/channels/$channel")" \
  || fail "no channel '$channel' at $releases. The channels are stable and edge."
sha="$(printf '%s' "$sha" | tr -d '[:space:]')"

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
curl -fsSL "$releases/builds/$sha/SHA256SUMS" -o "$tmp/SHA256SUMS" \
  || fail "the $channel channel's build ($sha) is not published."
want="$(awk -v f="$file" '$2 == f { print $1 }' "$tmp/SHA256SUMS")"
[ -n "$want" ] \
  || fail "the $channel channel's build ($sha) has no kite CLI for $os-$arch. Set KITE_CHANNEL to install from another channel."

curl -fsSL "$releases/builds/$sha/$file" -o "$tmp/kite" || fail "could not download $file."
if command -v sha256sum >/dev/null 2>&1; then
  got="$(sha256sum "$tmp/kite" | awk '{ print $1 }')"
else
  got="$(shasum -a 256 "$tmp/kite" | awk '{ print $1 }')"
fi
[ "$got" = "$want" ] || fail "$file does not match its sum in SHA256SUMS. Nothing was installed."

mkdir -p "$dir"
chmod 755 "$tmp/kite"
# A rename, so a kite running from $dir finishes on the file it started with.
mv -f "$tmp/kite" "$dir/kite"
printf 'installed %s\n' "$("$dir/kite" version)"
case ":$PATH:" in
  *":$dir:"*) ;;
  *) printf 'add %s to PATH to run it as kite\n' "$dir" ;;
esac
