#!/bin/bash
set -e

WP_PLUGINS_SRC="/usr/src/wordpress/wp-content/plugins"
WP_PLUGINS_DST="/var/www/html/wp-content/plugins"

# Copy WP core files from the image source to the volume (same as official entrypoint does)
# This avoids calling docker-entrypoint.sh which blocks waiting for DB before writing wp-config
if [ ! -e /var/www/html/index.php ]; then
    echo "[*] Copying WordPress core files..."
    tar cf - --one-file-system -C /usr/src/wordpress . | tar xf - -C /var/www/html
    chown -R www-data:www-data /var/www/html
fi

# Generate wp-config.php using WP-CLI (no DB connection needed for this step)
if [ ! -f /var/www/html/wp-config.php ]; then
    echo "[*] Generating wp-config.php..."
    wp config create \
        --path=/var/www/html \
        --dbname="${WORDPRESS_DB_NAME}" \
        --dbuser="${WORDPRESS_DB_USER}" \
        --dbpass="${WORDPRESS_DB_PASSWORD}" \
        --dbhost="${WORDPRESS_DB_HOST}" \
        --allow-root
fi

echo "[*] Copying kivicare-clinic-management-system..."
cp -r "$WP_PLUGINS_SRC/kivicare-clinic-management-system" "$WP_PLUGINS_DST/kivicare-clinic-management-system"

# Run setup (waits for DB, installs WP, activates plugins)
/setup.sh

echo "[*] Starting Apache..."
exec apache2-foreground