#!/bin/bash
set -euo pipefail

ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs"
mkdir -p "$LOGS"

cleanup() {
  rm -rf "$ROOT/repro/tmp"
}
trap cleanup EXIT

mkdir -p "$ROOT/repro/tmp"

if ! command -v node >/dev/null 2>&1; then
  echo "Node.js is required" | tee "$LOGS/error.log"
  exit 2
fi

if ! command -v npm >/dev/null 2>&1; then
  echo "npm is required" | tee "$LOGS/error.log"
  exit 2
fi

cd "$ROOT"

npm install --no-fund --no-audit --silent typescript ts-node tsx sinon >"$LOGS/npm_install.log" 2>&1

node -e "const esbuild=require('esbuild'); esbuild.build({entryPoints:['$ROOT/repro/mcp_workspace_trust_repro.ts'], bundle:true, platform:'node', format:'esm', outfile:'$ROOT/repro/mcp_workspace_trust_repro.bundle.mjs', tsconfigRaw:{compilerOptions:{experimentalDecorators:true}}}).catch(err=>{console.error(err); process.exit(1);});" >"$LOGS/esbuild.log" 2>&1

node -e "const fs=require('fs'); const path='$ROOT/repro/mcp_workspace_trust_repro.bundle.mjs'; let data=fs.readFileSync(path,'utf8'); data=data.replace(/\nexport \{[\s\S]*?\};\n/g,'\n'); fs.writeFileSync(path, data+'\nexport { checkVulnerable, checkPatched };\n');" >>"$LOGS/esbuild.log" 2>&1

cat > "$ROOT/repro/run_repro.mjs" <<'SCRIPT'
import { checkVulnerable, checkPatched } from './mcp_workspace_trust_repro.bundle.mjs';

const mode = process.argv[2];
if (!mode) {
  console.error('Usage: node run_repro.mjs <vulnerable|patched>');
  process.exit(2);
}

if (mode === 'vulnerable') {
  const ok = await checkVulnerable();
  if (!ok) {
    console.error('Expected vulnerable behavior but connection was blocked.');
    process.exit(1);
  }
  console.log('Vulnerable behavior observed: workspace-scoped server started without trust.');
  process.exit(0);
}

if (mode === 'patched') {
  const ok = await checkPatched();
  if (!ok) {
    console.error('Expected patched behavior but connection was allowed.');
    process.exit(1);
  }
  console.log('Patched behavior observed: workspace trust check blocked connection.');
  process.exit(0);
}

console.error('Unknown mode:', mode);
process.exit(2);
SCRIPT

VULN_LOG="$LOGS/vulnerable_run.log"
PATCH_LOG="$LOGS/patched_run.log"

node "$ROOT/repro/run_repro.mjs" vulnerable | tee "$VULN_LOG"

if ! git -C "$ROOT/vscode" cat-file -t cd11faec7b031b928bc5ec37f350d623ffb28713 >/dev/null 2>&1; then
  git -C "$ROOT/vscode" fetch --depth=500 origin cd11faec7b031b928bc5ec37f350d623ffb28713 >>"$LOGS/git_fetch.log" 2>&1
fi

git -C "$ROOT/vscode" checkout -q cd11faec7b031b928bc5ec37f350d623ffb28713

node -e "const esbuild=require('esbuild'); esbuild.build({entryPoints:['$ROOT/repro/mcp_workspace_trust_repro.ts'], bundle:true, platform:'node', format:'esm', outfile:'$ROOT/repro/mcp_workspace_trust_repro.bundle.mjs', tsconfigRaw:{compilerOptions:{experimentalDecorators:true}}}).catch(err=>{console.error(err); process.exit(1);});" >>"$LOGS/esbuild.log" 2>&1
node -e "const fs=require('fs'); const path='$ROOT/repro/mcp_workspace_trust_repro.bundle.mjs'; let data=fs.readFileSync(path,'utf8'); data=data.replace(/\nexport \{[\s\S]*?\};\n/g,'\n'); fs.writeFileSync(path, data+'\nexport { checkVulnerable, checkPatched };\n');" >>"$LOGS/esbuild.log" 2>&1

node "$ROOT/repro/run_repro.mjs" patched | tee "$PATCH_LOG"

git -C "$ROOT/vscode" checkout -q main

if grep -q "Vulnerable behavior observed" "$VULN_LOG" && grep -q "Patched behavior observed" "$PATCH_LOG"; then
  echo "Issue reproduced and fixed behavior verified." | tee "$LOGS/summary.log"
  exit 0
fi

echo "Issue not reproduced." | tee "$LOGS/summary.log"
exit 1
