#!/bin/bash
set -e

echo "Waiting for database to be ready..."
until mysqladmin ping -h "${DB_HOST}" -u"${DB_USERNAME}" -p"${DB_PASSWORD}" --skip-ssl --silent; do
  sleep 1
done
echo "Database is ready!"

# Fix permissions (PERMANENT SOLUTION for mounted volumes)
echo "Setting correct permissions on storage and bootstrap/cache..."
chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache
chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache

# Clear Laravel caches
php artisan config:clear
php artisan route:clear
php artisan view:clear


# Migrate (safe to run every boot — only runs pending migrations)
php artisan migrate --force

# Seed runs only the FIRST time (when DB has no accounts yet).
# Run manually instead if you prefer:  docker compose exec app php artisan db:seed --force
if [ "$(php artisan tinker --execute='echo \App\Models\Account::count();' 2>/dev/null | tail -1)" = "0" ]; then
  echo "Empty database detected — running seeders..."
  php artisan db:seed --force || true
fi


# Link storage (if not already linked)
php artisan storage:link || true

# Cache config
php artisan config:cache

# Start PHP-FPM
exec php-fpm
