#!/bin/bash
set -e

# Run the original WordPress entrypoint first (sets up wp-config.php, etc.)
# We source it in background and continue with our setup
docker-entrypoint.sh apache2-foreground &

# Wait for WordPress files to be ready
echo "[*] Waiting for WordPress to initialize..."
sleep 10

# Wait for database to be ready
echo "[*] Waiting for database connection..."
until nc -z -v -w30 db 3306 2>/dev/null; do
    echo "    Waiting for MySQL..."
    sleep 2
done
echo "[+] Database is ready"

# Additional wait for MySQL to fully accept connections
sleep 5

# Check if WordPress is already installed
if ! wp core is-installed --allow-root --path=/var/www/html 2>/dev/null; then
    echo "[*] Installing WordPress..."
    wp core install \
        --url="http://localhost:8088" \
        --title="CVE-2016-15041 Lab" \
        --admin_user="admin" \
        --admin_password="admin123" \
        --admin_email="admin@localhost.local" \
        --skip-email \
        --allow-root \
        --path=/var/www/html
    
    echo "[*] Activating MainWP Dashboard plugin..."
    wp plugin activate mainwp --allow-root --path=/var/www/html 2>/dev/null || echo "[!] Plugin activation had warnings (expected on first run)"
    
    echo ""
    echo "=========================================="
    echo " CVE-2016-15041 Lab Ready!"
    echo "=========================================="
    echo " WordPress:  http://localhost:8088"
    echo " Admin:      admin / admin123"
    echo ""
    echo " Vulnerable endpoint (no auth required):"
    echo " http://localhost:8088/wp-admin/admin-post.php?page=mainwp-setup&step=purchase_extension"
    echo ""
    echo " Test with nuclei:"
    echo " nuclei -t CVE-2016-15041.yaml -u http://localhost:8088"
    echo "=========================================="
else
    echo "[+] WordPress already installed"
fi

# Keep container running by waiting for the Apache process
wait

