#!/bin/sh
# Prepare the container, then hand over to supervisord (nginx, PHP-FPM, cron).
set -eu

cd /var/www/html

as_www() { su-exec www-data "$@"; }

# One-off commands (`docker run <image> php artisan key:generate --show`) run
# as-is, without the start-up checks below.
if [ "${1:-}" != "supervisord" ]; then
    exec "$@"
fi

if [ -z "${APP_KEY:-}" ]; then
    echo "ERROR: APP_KEY is not set." >&2
    echo "Generate one once and keep it in your secret store:" >&2
    echo "  docker run --rm <image> php artisan key:generate --show" >&2
    exit 1
fi

# storage/ may be empty (fresh container, or a new volume mounted over it).
mkdir -p storage/app/private storage/app/public storage/app/branding \
         storage/framework/cache/data storage/framework/sessions \
         storage/framework/views storage/logs bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache

php /usr/local/lib/pnlcs/render-env.php > .env
chown www-data:www-data .env
chmod 640 .env

# Wait for the database, so a pod that starts before MySQL does not crash-loop.
timeout="${DB_WAIT_TIMEOUT:-60}"
until as_www php -r '
    try {
        new PDO(
            sprintf("mysql:host=%s;port=%s", getenv("DB_HOST") ?: "127.0.0.1", getenv("DB_PORT") ?: "3306"),
            getenv("DB_USERNAME") ?: "", getenv("DB_PASSWORD") ?: "",
            [PDO::ATTR_TIMEOUT => 3]
        );
    } catch (Throwable $e) { fwrite(STDERR, $e->getMessage()."\n"); exit(1); }
'; do
    timeout=$((timeout - 3))
    if [ "$timeout" -le 0 ]; then
        echo "ERROR: database at ${DB_HOST:-127.0.0.1}:${DB_PORT:-3306} is not reachable." >&2
        exit 1
    fi
    echo "Waiting for the database..."
    sleep 3
done

# Migrations only: the install wizard seeds and creates the administrator.
if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then
    as_www php artisan migrate --force --no-interaction
fi

as_www php artisan optimize --no-interaction

exec "$@"
