#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$ROOT_DIR"

SANDBOX="$ROOT_DIR/sandbox/rho-key-revocation"
REPO="$SANDBOX/repo"
RHO_HOME_DIR="$SANDBOX/rho-home"
USER_ID="rho://id/github/rho-revoked"

rm -rf "$SANDBOX"
mkdir -p "$REPO"

git -C "$REPO" init >/dev/null
git -C "$REPO" config user.name "Rho Revocation Test"
git -C "$REPO" config user.email "revocation@example.test"
git -C "$REPO" config commit.gpgsign false

./rho repo init \
  --root "$REPO" \
  --repo-id rho://repo/local/key-revocation \
  --owner "$USER_ID" >/dev/null

RHO_HOME="$RHO_HOME_DIR" ./rho id init \
  --github rho-revoked \
  --display-name "Rho Revoked" \
  --generate-ssh-key >/dev/null

mkdir -p "$REPO/rho/messages/inbox/id/github/rho-revoked/request-revocation"
MESSAGE="$REPO/rho/messages/inbox/id/github/rho-revoked/request-revocation/request.yaml"
SIGNATURE="$REPO/rho/messages/inbox/id/github/rho-revoked/request-revocation/request.rhosig.yaml"
cat > "$MESSAGE" <<EOF
version: 1
request:
  id: request-revocation
  from: $USER_ID
  to: $USER_ID
  body: this signature should verify before revocation
EOF

RHO_HOME="$RHO_HOME_DIR" ./rho crypto sign "$MESSAGE" \
  --identity "$USER_ID" \
  --out "$SIGNATURE" >/dev/null

RHO_HOME="$RHO_HOME_DIR" ./rho crypto verify "$MESSAGE" \
  --signature "$SIGNATURE" \
  --identity "$USER_ID" \
  --repo-root "$REPO" >/dev/null

KEY_ID="$(sed -n 's/^  key_id: //p' "$SIGNATURE")"
test -n "$KEY_ID"
cat > "$REPO/rho/policy/revocations.yaml" <<EOF
version: 1
revocations:
  - identity: $USER_ID
    key_id: $KEY_ID
    reason: e2e compromised key
    revoked_at: "2026-06-15T00:00:00Z"
    revoked_by: $USER_ID
EOF

if RHO_HOME="$RHO_HOME_DIR" ./rho crypto verify "$MESSAGE" \
  --signature "$SIGNATURE" \
  --identity "$USER_ID" \
  --repo-root "$REPO" >"$SANDBOX/revoked-stdout.txt" 2>"$SANDBOX/revoked-stderr.txt"; then
  echo "revoked signature unexpectedly verified" >&2
  exit 1
fi
grep -q "signature key revoked" "$SANDBOX/revoked-stderr.txt"
grep -q "$KEY_ID" "$SANDBOX/revoked-stderr.txt"

echo "inspect sandbox: $SANDBOX"
find "$SANDBOX" \
  -path "*/.git" -prune -o \
  -maxdepth 6 -type f -print | sort
echo "rho key revocation e2e passed"
