#!/bin/bash
set -euo pipefail

cd /var/www/html

echo "[flixcooks] Waiting for database..."
TRIES=0
MAX_TRIES="${DB_WAIT_MAX_TRIES:-30}"

until php scripts/db-check.php >/dev/null 2>&1; do
  TRIES=$((TRIES + 1))
  if [ "$TRIES" -ge "$MAX_TRIES" ]; then
    echo "[flixcooks] Database not reachable after ${MAX_TRIES} attempts." >&2
    exit 1
  fi
  sleep 2
done

echo "[flixcooks] Applying schema..."
php -r "require 'helpers.php'; require_database(); echo \"schema ok\n\";"

if [ "${RUN_DB_SEED:-false}" = "true" ]; then
  echo "[flixcooks] Seeding recipes from data/recipes.json..."
  php scripts/db-seed.php
fi

echo "[flixcooks] Starting Apache..."
exec "$@"
