#!/bin/sh
set -e

cd /var/www/html

if [ ! -f .env ]; then
    cp .env.docker.example .env
fi

if [ ! -f vendor/autoload.php ]; then
    composer install --no-interaction --no-progress
fi

if [ ! -d node_modules/puppeteer ]; then
    npm install --no-audit --no-fund
fi

echo "Waiting for MySQL at ${DB_HOST:-mysql}:${DB_PORT:-3306}..."
until mysqladmin ping -h "${DB_HOST:-mysql}" -P "${DB_PORT:-3306}" -u"${DB_USERNAME:-wmamis}" -p"${DB_PASSWORD:-secret}" --skip-ssl --silent >/dev/null 2>&1; do
    sleep 1
done
# On a genuinely fresh volume, MySQL briefly starts an internal-only instance to run
# docker-entrypoint-initdb.d scripts, shuts it down, then starts the real listener -
# mysqladmin ping above can succeed against that transient instance moments before
# the real one is up. Settle briefly before trusting it.
sleep 5

if ! grep -q "^APP_KEY=base64" .env; then
    php artisan key:generate --ansi
fi

php artisan migrate --force || echo "WARNING: some migrations failed to run. The Osa module's migrations (osa_db connection) expect the legacy new-osa/backend CodeIgniter app's schema to already exist in the osa_app database. This should normally be provisioned automatically by the osa-backend service (depends_on ensures it runs first) - check 'docker compose logs osa-backend' if this warning appears. Continuing startup anyway."

# Roles and permissions are configuration (config/rbac.php); bring the database in
# line with it on every start so a new permission is never missing after a deploy.
php artisan rbac:sync --force || echo "WARNING: rbac:sync failed - check the output above (a retired role that still has users blocks the sync until those users are reassigned)."

if [ ! -L public/storage ]; then
    php artisan storage:link
fi

chown -R www-data:www-data storage bootstrap/cache

# Lets other containers (queue, nginx) wait until setup/migrations are actually done,
# not just until this container has started.
touch /tmp/app-ready

exec "$@"
