#!/bin/sh
set -e

# Generate application key if missing
if ! grep -q "^APP_KEY=base64:" /var/www/.env 2>/dev/null; then
    echo "Generating application key..."
    php artisan key:generate --force
fi

# Run pending migrations only (Laravel tracks executed migrations in the 'migrations' table and will never drop or overwrite existing tables/data)
echo "Checking for pending migrations..."
php artisan migrate --force

# Seed database only on initial setup (skips if roles already exist to preserve existing data)
ROLES_COUNT=$(php artisan tinker --execute="echo \Spatie\Permission\Models\Role::count();" 2>/dev/null | tr -dc '0-9')
if [ "$ROLES_COUNT" = "0" ] || [ -z "$ROLES_COUNT" ]; then
    echo "Initial setup detected. Running seeders..."
    php artisan db:seed --force
else
    echo "Database already seeded ($ROLES_COUNT roles found). Skipping seeders to preserve existing data."
fi

# Create storage symlink if missing
if [ ! -e /var/www/public/storage ]; then
    echo "Creating storage symlink..."
    php artisan storage:link || true
fi

echo "Starting PHP-FPM..."
exec "$@"
