#!/bin/bash

WP="/var/www/html"
WP_URL="http://localhost:8080"
WP_ADMIN="admin"
WP_PASS="admin"
WP_EMAIL="admin@example.com"
WP_TITLE="CVE-2026-2991 Test"

DB_HOST="${WORDPRESS_DB_HOST:-db}"

# Wait for MySQL TCP port — pure bash, no client binary, no auth
echo "[*] Waiting for database on ${DB_HOST}:3306..."
while ! (echo > /dev/tcp/${DB_HOST}/3306) 2>/dev/null; do
    sleep 2
done
echo "[+] Port open. Giving MySQL 3 seconds to finish init..."
sleep 3
echo "[+] Database is up."

if wp core is-installed --path="$WP" --allow-root > /dev/null 2>&1; then
    echo "[+] WordPress already installed, skipping setup."
    exit 0
fi

echo "[*] Installing WordPress..."
wp core install \
    --path="$WP" \
    --url="$WP_URL" \
    --title="$WP_TITLE" \
    --admin_user="$WP_ADMIN" \
    --admin_password="$WP_PASS" \
    --admin_email="$WP_EMAIL" \
    --skip-email \
    --allow-root

echo "[*] Enabling pretty permalinks (required for REST API)..."
wp rewrite structure '/%postname%/' --path="$WP" --allow-root --skip-plugins
wp rewrite flush --path="$WP" --allow-root --skip-plugins

echo "[*] Activating vulnerable plugin..."
wp plugin activate kivicare-clinic-management-system --path="$WP" --allow-root --skip-plugins

echo "[*] Verifying active plugins..."
wp plugin list --path="$WP" --allow-root --fields=name,status

echo "[*] Seeding clinic, doctors and patients..."
wp eval-file /seed.php --path="$WP" --allow-root

echo "[+] Done — http://localhost:8080  |  Admin: http://localhost:8080/wp-admin ($WP_ADMIN / $WP_PASS)"
echo "[+] Doctors  : dr.harris / dr.chen / dr.okonkwo  (password: Doctor@123)"
echo "[+] Patients : james.ford / sofia.reyes / oliver.knight / amara.diallo / dan.walsh  (password: Patient@123)"