#!/bin/sh
set -e
cd /var/www/html

# Build config.php from env (container template) if not supplied
if [ ! -f config/config.php ]; then
  cp config/config.docker.php config/config.php
fi

mkdir -p storage/logs
chown -R www-data:www-data storage 2>/dev/null || true
chmod -R 775 storage 2>/dev/null || true

# Wait for the database
DB_H="${DB_HOST:-db}"; DB_P="${DB_PORT:-3306}"
echo "Waiting for database ${DB_H}:${DB_P}..."
i=0
until php -r '$c=@fsockopen(getenv("DB_HOST")?:"db",(int)(getenv("DB_PORT")?:3306),$e,$s,2); exit($c?0:1);' 2>/dev/null; do
  i=$((i+1)); [ "$i" -gt 60 ] && echo "DB not reachable, continuing anyway" && break
  sleep 2
done

# Apply schema + migrations (idempotent) unless disabled
if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then
  php bin/migrate.php || echo "migrate step reported issues (often benign)"
fi

exec "$@"
