#!/bin/sh
# Install Raddu:  curl -fsSL https://raddu.dev/install.sh | sh
# Downloads the binary for this machine, checks it against the release's
# SHA256SUMS (and that file's minisign signature when minisign is installed),
# and puts it in ~/.local/bin (override with RADDU_INSTALL_DIR).
set -eu
BASE=${RADDU_BASE:-${UNDO_BASE:-https://raddu.dev/releases/latest}}
DIR=${RADDU_INSTALL_DIR:-${UNDO_INSTALL_DIR:-$HOME/.local/bin}}
PUBKEY=RWT+I/m6yw0fpjh7tWTxAoO0FG0mCr+NC5hqxTkmO6jd0qype7ylxH92

say() { printf '%s\n' "$*"; }
die() { printf 'raddu install: %s\n' "$*" >&2; exit 1; }

case $(uname -s) in Linux) os=linux ;; Darwin) os=darwin ;; *) die "unsupported OS $(uname -s) (Linux and macOS only)" ;; esac
case $(uname -m) in x86_64|amd64) arch=amd64 ;; aarch64|arm64) arch=arm64 ;; *) die "unsupported CPU $(uname -m)" ;; esac
command -v curl >/dev/null || die "curl is required"

tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
bin=raddu-$os-$arch
say "Downloading Raddu ($os/$arch)…"
curl -fsSL "$BASE/$bin" -o "$tmp/$bin" || die "download failed: $BASE/$bin"
curl -fsSL "$BASE/SHA256SUMS" -o "$tmp/SHA256SUMS" || die "download failed: $BASE/SHA256SUMS"

if command -v minisign >/dev/null; then
	curl -fsSL "$BASE/SHA256SUMS.minisig" -o "$tmp/SHA256SUMS.minisig" || die "signature download failed"
	minisign -Vq -P "$PUBKEY" -m "$tmp/SHA256SUMS" || die "SIGNATURE CHECK FAILED — not installing"
	say "✓ signature verified"
fi

want=$(grep " $bin\$" "$tmp/SHA256SUMS" | cut -d' ' -f1)
[ -n "$want" ] || die "$bin missing from SHA256SUMS"
if command -v sha256sum >/dev/null; then got=$(sha256sum "$tmp/$bin" | cut -d' ' -f1)
else got=$(shasum -a 256 "$tmp/$bin" | cut -d' ' -f1); fi
[ "$got" = "$want" ] || die "CHECKSUM MISMATCH — not installing"
say "✓ checksum verified"

mkdir -p "$DIR"
chmod +x "$tmp/$bin"
mv "$tmp/$bin" "$DIR/raddu"
say "✓ installed $("$DIR/raddu" version 2>/dev/null || echo raddu) → $DIR/raddu"
[ -x "$DIR/undo" ] && "$DIR/undo" version 2>/dev/null | grep -q "^undo v0\.1" && say "Note: $DIR/undo is the old name of this tool (Undo v0.1). Your setup keeps working with raddu; you can delete the old binary."

case ":$PATH:" in *":$DIR:"*) ;; *) say "" ; say "Add $DIR to your PATH:  export PATH=\"$DIR:\$PATH\"" ;; esac
command -v docker >/dev/null || say "Note: \`raddu init\` uses Docker for local storage and the restore test — install Docker first."
say ""
say "Next, in your project:"
say "  raddu check    what could an agent destroy here? (read-only, sends nothing)"
say "  raddu init     take a tested restore point and protect every agent session"
say ""
say "Raddu is in public beta: free, and we want to hear what breaks."
say "  raddu feedback \"what happened\"   shows exactly what it sends, asks first"
say "  guide: https://raddu.dev/learn/get-started/beta.html"
