#!/bin/sh
# karmadue-guard 0.1.0 installer. Checks npm/npx/pnpm/yarn/pip/uv installs with KarmaDue before they run.
# Usage: curl -fsSL https://karmadue.expo.app/guard/install.sh | sh
# Installs to ~/.karmadue/guard and ~/.karmadue/shims. Changes no shell files; prints the one PATH line to add.
# Needs Node 18+ and curl. Every file is checked against the SHA-256 pinned below before it is used.
set -eu
BASE="${KARMADUE_GUARD_BASE:-https://karmadue.expo.app/guard}"
DEST="${KARMADUE_HOME:-$HOME/.karmadue}"
command -v node >/dev/null 2>&1 || { echo "karmadue-guard: Node 18+ is required (node not found)." >&2; exit 1; }
node -e 'process.exit(+process.versions.node.split(".")[0] >= 18 ? 0 : 1)' || { echo "karmadue-guard: Node 18+ is required (found $(node -v))." >&2; exit 1; }
sha() { if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | cut -d" " -f1; else shasum -a 256 "$1" | cut -d" " -f1; fi; }
mkdir -p "$DEST/guard/lib"
get() { # url-path dest sha
  tmp="$2.part"
  curl -fsSL "$BASE/$1" -o "$tmp" || { echo "karmadue-guard: download failed: $BASE/$1" >&2; exit 1; }
  got="$(sha "$tmp")"
  [ "$got" = "$3" ] || { rm -f "$tmp"; echo "karmadue-guard: checksum mismatch for $1 (expected $3, got $got). Nothing installed." >&2; exit 1; }
  mv "$tmp" "$2"
}
get karmadue-guard.js "$DEST/guard/karmadue-guard.js" 5f68bc9b456d73ea4d17d323e1f20d767d5723c87280a4a84aece4f883d27894
get lib/karmadue-preinstall.js "$DEST/guard/lib/karmadue-preinstall.js" b4267daf461078886f7f4a76d4386921bd578fa6109bff5b65f847384dccf764
chmod +x "$DEST/guard/karmadue-guard.js"
KARMADUE_SHIM_DIR="$DEST/shims" node "$DEST/guard/karmadue-guard.js" install-shims "$DEST/shims" 2>/dev/null
echo "karmadue-guard 0.1.0 installed in $DEST (shims: npm npx pnpm pnpx yarn pip pip3 uv uvx)."
echo "Turn it on for this shell, and add the same line to ~/.bashrc or ~/.zshrc to keep it:"
echo "  export PATH=\"$DEST/shims:\$PATH\""
echo "Test: npm install event-stream@3.3.6   (should be BLOCKED).  Off for one command: KARMADUE_DISABLE=1 npm ..."
