#!/bin/sh
# Installs the rapadura CLI. Usage: curl -fsSL https://agents.rapadura.net/install.sh | sh
set -eu
BASE="${RAPADURA_GATEWAY:-https://agents.rapadura.net}"
case "$BASE" in
  https://?*) ;;
  *) echo "RAPADURA_GATEWAY must use HTTPS" >&2; exit 1 ;;
esac
BASE=${BASE%/}
valid_digest() {
  [ "${#1}" -eq 64 ] || return 1
  case "$1" in *[!0123456789abcdefABCDEF]*) return 1 ;; esac
}
pin="${RAPADURA_SHA256:-}"
if [ -n "$pin" ]; then
  valid_digest "$pin" || { echo "RAPADURA_SHA256 must be a 64-character SHA-256 digest" >&2; exit 1; }
  pin=$(printf '%s' "$pin" | tr '[:upper:]' '[:lower:]')
fi
if command -v sha256sum >/dev/null 2>&1; then
  hash_tool=sha256sum
elif command -v shasum >/dev/null 2>&1; then
  hash_tool=shasum
else
  echo "SHA-256 verification requires sha256sum or shasum" >&2
  exit 1
fi
os=$(uname -s | tr '[:upper:]' '[:lower:]')
arch=$(uname -m)
case "$arch" in
  x86_64|amd64) arch=amd64 ;;
  arm64|aarch64) arch=arm64 ;;
  *) echo "unsupported architecture: $arch" >&2; exit 1 ;;
esac
case "$os" in
  linux|darwin) ;;
  mingw*|msys*|cygwin*) os=windows ;;
  *) echo "unsupported OS: $os" >&2; exit 1 ;;
esac
ext=""; [ "$os" = windows ] && ext=".exe"
filename="rapadura_${os}_${arch}${ext}"
url="$BASE/dl/$filename"
dest="${RAPADURA_INSTALL_DIR:-$HOME/.local/bin}"
mkdir -p "$dest"
# Stage inside the destination so the final replacement is a same-filesystem
# rename. Verification failures never replace an existing installation.
tmp_dir=$(mktemp -d "$dest/.rapadura-install.XXXXXXXX")
trap 'rm -rf "$tmp_dir"' 0
trap 'exit 1' HUP INT TERM
tmp="$tmp_dir/$filename"
manifest="$tmp_dir/SHA256SUMS"
echo "Downloading $url"
curl --proto '=https' --proto-redir '=https' -fsSL -o "$manifest" "$BASE/dl/SHA256SUMS"
expected=$(awk -v target="$filename" '
  {
    hash = substr($0, 1, 64)
    separator = substr($0, 65, 2)
    name = substr($0, 67)
    if (length(hash) != 64 || hash ~ /[^0123456789abcdefABCDEF]/ ||
        (separator != "  " && separator != " *") || name == "" ||
        name ~ /[[:space:]]/ || seen[name]++) {
      invalid = 1
    }
    if (name == target) { matches++; digest = tolower(hash) }
  }
  END {
    if (invalid || matches != 1) exit 1
    print digest
  }
' "$manifest") || { echo "Invalid SHA256SUMS manifest or missing exact artifact entry" >&2; exit 1; }
if [ -n "$pin" ] && [ "$pin" != "$expected" ]; then
  echo "Release manifest does not match RAPADURA_SHA256" >&2
  exit 1
fi
curl --proto '=https' --proto-redir '=https' -fsSL -o "$tmp" "$url"
if [ "$hash_tool" = sha256sum ]; then
  hash_output=$(sha256sum "$tmp")
else
  hash_output=$(shasum -a 256 "$tmp")
fi
actual=${hash_output%% *}
valid_digest "$actual" || { echo "SHA-256 tool returned an invalid digest" >&2; exit 1; }
actual=$(printf '%s' "$actual" | tr '[:upper:]' '[:lower:]')
if [ "$actual" != "$expected" ]; then
  echo "SHA-256 verification failed for $filename" >&2
  exit 1
fi
chmod 0755 "$tmp"
mv "$tmp" "$dest/rapadura$ext"
echo "Installed $dest/rapadura$ext"
case ":$PATH:" in
  *":$dest:"*) ;;
  *) echo "Add $dest to your PATH, e.g.:  export PATH=\"$dest:\$PATH\"" ;;
esac
echo
echo "Next:  rapadura login"
echo "Then:  rapadura publish ./site --site <slug> --create"
echo "Docs:  $BASE/docs/"
