#!/bin/sh
# SPDX-FileCopyrightText: 2026 Keres Project
# SPDX-License-Identifier: 0BSD
#
# kpm/install.sh -- end-user bootstrap: install the kpm binary only.
#
#     curl -fsSL https://kereslang.com/kpm/install.sh | sh
#
# Installs:
#     ~/.local/bin/kpm
#
# Package signing keys are not installed here; `kpm install` fetches the
# catalog-listed .pub from B2 (or you use `kpm install-local` with
# --trusted-key). Re-running overwrites the same path. No sudo.

set -eu

ORIGIN="${KPM_REPO_ORIGIN:-https://kereslang.com}"

# 64-hex SHA-256 of kpm-linux-x86-64 (maintainers: `make www` refreshes the default).
# Override with env KPM_BIN_SHA256_PIN for local testing.
KPM_BIN_SHA256_PIN="${KPM_BIN_SHA256_PIN:-02c37da6756a3bd083ca4bac1fe8a4dcea9aee82b360b28ddb2d0f48b3e29a6f}"

MAX_BIN_BYTES=$(( 16 * 1024 * 1024 ))

die() { printf 'install.sh: %s\n' "$*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "missing tool: $1"; }
need curl
need install
need mktemp
need sha256sum

case "$ORIGIN" in
    https://*) ;;
    *) die "KPM_REPO_ORIGIN must be https:// (got: $ORIGIN)" ;;
esac

PREFIX="${HOME:-/}/.local"
BIN_DIR="$PREFIX/bin"

[ -n "${HOME:-}" ] || die "\$HOME not set; refusing to install into /"

mkdir -p -- "$BIN_DIR"

TMP=$(mktemp -d -t kpm-install.XXXXXXXX)
chmod 0700 -- "$TMP"
cleanup() { rm -rf -- "$TMP"; }
trap cleanup EXIT INT TERM HUP

fetch() {
    url=$1; out=$2; cap=$3
    case "$url" in
        "$ORIGIN"/*) ;;
        *) die "refusing to fetch outside origin ($ORIGIN): $url" ;;
    esac
    curl --proto =https --tlsv1.2 \
         --silent --show-error --fail \
         --max-time 60 --max-filesize "$cap" \
         -o "$out" -- "$url" \
        || die "fetch failed: $url"
    sz=$(stat -c '%s' -- "$out")
    [ "$sz" -le "$cap" ] || die "$url: size $sz exceeds cap $cap"
    [ "$sz" -gt 0 ]      || die "$url: empty response"
}

printf 'kpm bootstrap: origin=%s\n' "$ORIGIN"

[ -n "$KPM_BIN_SHA256_PIN" ] \
    || die "verification failed: SHA-256 pin is empty (bootstrap misconfigured)"

fetch "$ORIGIN/kpm/kpm-linux-x86-64" "$TMP/kpm" "$MAX_BIN_BYTES"

got=$(sha256sum -- "$TMP/kpm" | awk '{print $1}')
[ "$got" = "$KPM_BIN_SHA256_PIN" ] \
    || die "verification failed: kpm binary SHA-256 does not match pinned hash
  expected: $KPM_BIN_SHA256_PIN
  obtained: $got"

printf '  kpm binary sha256: ok (matches pin)\n'

install -m 0755 -- "$TMP/kpm" "$BIN_DIR/kpm"

cat <<EOF

Installed: $BIN_DIR/kpm

Add $BIN_DIR to your PATH if needed. Then:

  kpm list
  kpm install hello
  kpm installed
  kpm remove hello
EOF
