#!/bin/bash

echo "Waiting for WordPress to be ready..."
sleep 10

echo -e "\n1. Checking if WordPress is accessible..."
curl -s -o /dev/null -w "HTTP Status: %{http_code}\n" http://localhost:8080

echo -e "\n2. Setting up WordPress (if needed)..."
docker exec adstxt-guru-connect-wordpress-1 wp core install \
  --url=http://localhost:8080 \
  --title="Test Site" \
  --admin_user=admin \
  --admin_password=admin123 \
  --admin_email=admin@example.com \
  --allow-root 2>/dev/null || echo "WordPress already installed"

echo -e "\n3. Activating the plugin..."
docker exec adstxt-guru-connect-wordpress-1 wp plugin activate adstxt-guru-connect --allow-root

echo -e "\n4. Checking plugin status..."
docker exec adstxt-guru-connect-wordpress-1 wp plugin list --allow-root | grep adstxt

echo -e "\n5. Testing CSRF vulnerability (should fail with 1.1.2)..."
echo "Creating test form without nonce..."
cat > /tmp/test_csrf.html <<EOF
<html>
<body onload="document.forms[0].submit()">
<form action="http://localhost:8080/wp-admin/admin.php?page=adstxt-guru-connect" method="POST">
  <input type="hidden" name="atg-connect-path" value="/etc/passwd" />
  <input type="hidden" name="atg-connect-custom" value="HACKED" />
</form>
</body>
</html>
EOF

echo -e "\n6. Getting admin cookie for testing..."
COOKIE=$(curl -s -c - -X POST http://localhost:8080/wp-login.php \
  -d "log=admin&pwd=admin123&wp-submit=Log+In" \
  | grep wordpress_logged_in | awk '{print $6"="$7}')

echo -e "\n7. Testing legitimate request WITH nonce (should work)..."
# First get the page with nonce
RESPONSE=$(curl -s -b "$COOKIE" http://localhost:8080/wp-admin/admin.php?page=adstxt-guru-connect)
NONCE=$(echo "$RESPONSE" | grep -o 'name="atg_connect_custom_nonce" value="[^"]*"' | sed 's/.*value="\([^"]*\)".*/\1/')

if [ ! -z "$NONCE" ]; then
  echo "Found nonce: $NONCE"
  echo "Testing custom content update with valid nonce..."
  curl -s -X POST -b "$COOKIE" \
    http://localhost:8080/wp-admin/admin.php?page=adstxt-guru-connect \
    -d "atg-connect-custom=example.com, 12345, DIRECT&atg_connect_custom_nonce=$NONCE" \
    | grep -o "Custom ads.txt records updated successfully" && echo "✓ Update successful with valid nonce"
else
  echo "✗ Could not find nonce field (security may be missing)"
fi

echo -e "\n8. Testing malicious request WITHOUT nonce (should fail)..."
curl -s -X POST -b "$COOKIE" \
  http://localhost:8080/wp-admin/admin.php?page=adstxt-guru-connect \
  -d "atg-connect-path=/etc/passwd&atg-connect-custom=HACKED" \
  | grep -o "Security error" && echo "✓ Attack blocked - CSRF protection working!" || echo "✗ No security error found"

echo -e "\nTest complete!"
echo "You can access WordPress at: http://localhost:8080"
echo "Admin login: admin / admin123"