#!/bin/sh
# Invoice Match app entrypoint:
#   1. ensure vendor/ exists (dev bind-mounts can hide the image's vendor),
#   2. wait for MySQL to accept connections,
#   3. run framework + Shield + app migrations (php spark migrate --all),
#   4. optionally seed on first boot,
#   5. hand off to php-fpm (the container CMD).
set -e

APP_DIR=/var/www/html
cd "$APP_DIR"

# 1. Dependencies -------------------------------------------------------------
if [ ! -f "$APP_DIR/vendor/autoload.php" ]; then
    echo "[entrypoint] vendor/ missing — running composer install..."
    composer install --no-interaction --no-progress --prefer-dist --working-dir="$APP_DIR"
fi

# 1b. Writable permissions ----------------------------------------------------
# The ./app bind mount is host-owned, so the image-time chown is shadowed.
# Fix it at runtime (entrypoint runs as root) so php-fpm (www-data) can write.
mkdir -p "$APP_DIR"/writable/cache "$APP_DIR"/writable/logs \
         "$APP_DIR"/writable/session "$APP_DIR"/writable/uploads \
         "$APP_DIR"/writable/temp "$APP_DIR"/writable/debugbar
chown -R www-data:www-data "$APP_DIR"/writable 2>/dev/null || true
chmod -R ug+rwx "$APP_DIR"/writable 2>/dev/null || true

# 2. Wait for MySQL -----------------------------------------------------------
# Probe with PHP/PDO — the php-fpm image has pdo_mysql but no mysql client tools.
DB_HOST="${MYSQL_HOST:-mysql}"
echo "[entrypoint] waiting for MySQL at ${DB_HOST}..."
tries=0
until php -r '
    $h=getenv("MYSQL_HOST")?:"mysql";
    $d=getenv("MYSQL_DATABASE")?:"invoice_match";
    $u=getenv("MYSQL_USER")?:"root";
    $p=getenv("MYSQL_PASSWORD")?:"";
    try { new PDO("mysql:host=$h;dbname=$d", $u, $p); exit(0); }
    catch (Throwable $e) { exit(1); }
' >/dev/null 2>&1; do
    tries=$((tries + 1))
    if [ "$tries" -gt 60 ]; then
        echo "[entrypoint] MySQL did not become ready in time." >&2
        exit 1
    fi
    sleep 2
done
echo "[entrypoint] MySQL is up."

# 3. Migrations (framework + Shield + Settings + app) -------------------------
echo "[entrypoint] running migrations..."
php spark migrate --all

# 4. Optional first-boot seed -------------------------------------------------
if [ "${SEED_ON_BOOT:-false}" = "true" ]; then
    echo "[entrypoint] seeding initial data..."
    php spark db:seed InitialSeeder
fi

# 5. Start the process passed as CMD (php-fpm) --------------------------------
echo "[entrypoint] starting: $*"
exec "$@"
