#!/bin/sh
# Prepare the container, then hand over to supervisord.
set -e
cd /var/www/html

if [ -z "$APP_KEY" ]; then
  echo "APP_KEY is not set. Generate one once (php artisan key:generate --show) and keep it safe: encrypted data depends on it." >&2
  exit 1
fi

# Wait for the database (up to 60s) so migrations do not race the DB container.
i=0
until php -r 'try { new PDO("mysql:host=".getenv("DB_HOST").";port=".(getenv("DB_PORT") ?: 3306), getenv("DB_USERNAME"), getenv("DB_PASSWORD")); } catch (Throwable $e) { exit(1); }'; do
  i=$((i+1)); [ "$i" -ge 30 ] && { echo "Database not reachable" >&2; exit 1; }
  sleep 2
done

php artisan package:discover --ansi
php artisan storage:link >/dev/null 2>&1 || true
if [ "${RUN_MIGRATIONS:-true}" = "true" ]; then
  php artisan migrate --force
fi
php artisan config:cache
php artisan route:cache
php artisan view:cache
chown -R www-data:www-data storage bootstrap/cache

exec "$@"
