#!/bin/sh
set -eu

WP_PATH="${WP_PATH:-/var/www/html}"
SITE_URL="${SITE_URL:-http://127.0.0.1:8080}"
SITE_TITLE="${SITE_TITLE:-My Right Horse Compatibility}"
WP_ADMIN_USER="${WP_ADMIN_USER:-wp-test-admin}"
WP_ADMIN_PASSWORD="${WP_ADMIN_PASSWORD:-wp-test-password}"
WP_ADMIN_EMAIL="${WP_ADMIN_EMAIL:-wp-test-admin@example.com}"
PLUGIN_SLUG="${PLUGIN_SLUG:-my-right-horse}"

cd "$WP_PATH"

if [ ! -f "$WP_PATH/wp-config.php" ]; then
  echo "wp-config.php is missing; start the WordPress container first."
  exit 1
fi

until wp db check --path="$WP_PATH" --allow-root >/dev/null 2>&1; do
  sleep 2
done

if ! wp core is-installed --path="$WP_PATH" --allow-root >/dev/null 2>&1; then
  wp core install \
    --url="$SITE_URL" \
    --title="$SITE_TITLE" \
    --admin_user="$WP_ADMIN_USER" \
    --admin_password="$WP_ADMIN_PASSWORD" \
    --admin_email="$WP_ADMIN_EMAIL" \
    --skip-email \
    --path="$WP_PATH" \
    --allow-root
fi

wp rewrite structure '/%postname%/' --hard --path="$WP_PATH" --allow-root >/dev/null 2>&1 || true
wp rewrite flush --hard --path="$WP_PATH" --allow-root >/dev/null 2>&1 || true

if ! wp plugin is-active "$PLUGIN_SLUG" --path="$WP_PATH" --allow-root >/dev/null 2>&1; then
  wp plugin activate "$PLUGIN_SLUG" --path="$WP_PATH" --allow-root
fi

page_id="$(wp post list --post_type=page --name=horse-listings --field=ID --path="$WP_PATH" --allow-root | head -n 1)"

if [ -z "${page_id:-}" ]; then
  wp post create \
    --post_type=page \
    --post_title='Horse Listings' \
    --post_name='horse-listings' \
    --post_status=publish \
    --post_content='[horse_listing]' \
    --path="$WP_PATH" \
    --allow-root
else
  wp post update "$page_id" \
    --post_content='[horse_listing]' \
    --path="$WP_PATH" \
    --allow-root
fi
