#!/bin/bash
set -euo pipefail

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

exec > >(tee -a "$LOGS/verify_fix.log")
exec 2>&1

log() { echo "[$(date -Iseconds)] $*"; }
fail() { log "FAIL: $*"; exit 1; }

VULN_TAG="v26.04.28-02"
FIXED_TAG="v26.04.28-03"
BASE_URL="https://raw.githubusercontent.com/dotCMS/core"

FILES=(
  "dotCMS/src/main/java/com/dotcms/publisher/business/PublishAuditAPIImpl.java"
  "dotCMS/src/main/java/com/dotcms/publisher/business/PublisherQueueJob.java"
  "dotCMS/src/main/java/com/dotcms/publisher/pusher/AuthCredentialPushPublishUtil.java"
  "dotCMS/src/main/java/com/dotcms/rest/AuditPublishingResource.java"
)

log "Verifying proposed fix against vulnerable tag $VULN_TAG and fixed tag $FIXED_TAG"

[ -f "$PATCH" ] || fail "Patch file not found: $PATCH"

TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

mkdir -p "$TMPDIR/vulnerable" "$TMPDIR/fixed" "$TMPDIR/patched"

log "Downloading vulnerable source files from $VULN_TAG ..."
for f in "${FILES[@]}"; do
  mkdir -p "$TMPDIR/vulnerable/$(dirname "$f")" "$TMPDIR/fixed/$(dirname "$f")"
  curl -fsSL "$BASE_URL/$VULN_TAG/$f" -o "$TMPDIR/vulnerable/$f" || fail "Could not download $f from $VULN_TAG"
  curl -fsSL "$BASE_URL/$FIXED_TAG/$f" -o "$TMPDIR/fixed/$f" || fail "Could not download $f from $FIXED_TAG"
done

log "Copying vulnerable files into patched directory ..."
cp -r "$TMPDIR/vulnerable/." "$TMPDIR/patched/"

log "Applying proposed_fix.diff to patched directory ..."
if ! patch -p1 -d "$TMPDIR/patched" < "$PATCH"; then
  fail "Patch did not apply cleanly"
fi

log "Comparing patched files to the official fixed tag ..."
if diff -qr "$TMPDIR/patched" "$TMPDIR/fixed" > "$TMPDIR/diff_report.txt"; then
  log "PASS: patched source matches the fixed version ($FIXED_TAG)"
else
  log "Differences between patched and fixed source:"
  cat "$TMPDIR/diff_report.txt"
  fail "Patched source does not match fixed version"
fi

log "All checks passed."
exit 0
