#!/bin/sh
set -e

echo "==> Starting El Captain deployment..."

# Ensure storage directories exist
mkdir -p \
    storage/framework/cache/data \
    storage/framework/sessions \
    storage/framework/views \
    storage/logs \
    bootstrap/cache

# Fix permissions — run as root before supervisord drops to www-data
chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache
# Ensure log file exists and is writable (CapRover volumes can remount with wrong owner)
touch storage/logs/laravel.log
chown www-data:www-data storage/logs/laravel.log
chmod 664 storage/logs/laravel.log

# Build .env from Docker env vars (CapRover passes them as container env)
: > .env
# Anything not matched here is absent from .env, and `config:cache` below then bakes
# the config default — usually null — into the compiled config for the life of the
# container. That is why PAYMOB_* was silently missing: the gateway read null
# credentials and failed closed with no error anywhere. Add a prefix here whenever
# you add one to config/services.php.
env | grep -E "^(APP_|DB_|LOG_|SESSION_|CACHE_|QUEUE_|FILESYSTEM_|BROADCAST_|MAIL_|TRUSTED_|BCRYPT_|PLATFORM_|ADMIN_|ACADEMY_|RUN_|WHATSAPP_|MESSAGING_|PAYMOB_|FIREBASE_|SMS_|VAPID_|CHECKIN_)" | sort | sed 's/=\(.*\)/="\1"/' >> .env

# Ensure APP_KEY line exists (key:generate needs it to write to)
if ! grep -q '^APP_KEY=' .env 2>/dev/null; then
    echo 'APP_KEY=""' >> .env
fi

# Auto-generate APP_KEY if not set
if ! grep -q '^APP_KEY="base64:' .env 2>/dev/null; then
    echo "==> Generating APP_KEY..."
    php artisan key:generate --force --no-interaction
fi

# Create storage link if not exists
if [ ! -L public/storage ]; then
    php artisan storage:link --no-interaction
fi

# Flush stale application cache from previous deploy
php artisan cache:clear 2>/dev/null || true

# Cache configuration for production
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

# Run pending migrations.
#
# This used to log a warning and continue. That is the worst possible outcome: the
# container boots and serves traffic against a schema the code no longer matches,
# and because the failed migration is never recorded as run, every migration queued
# behind it is blocked on every subsequent deploy — silently, forever. The failure
# surfaces weeks later as a missing column in an unrelated feature.
#
# Failing the boot keeps the previous healthy container serving while the error is
# visible in the deploy log, which is the outcome you actually want.
if ! php artisan migrate --force --no-interaction; then
    echo "==> FATAL: Migration failed. Refusing to start against an unmigrated schema."
    echo "==> If 'Insufficient privilege', ensure DB_USERNAME owns all tables:"
    echo "==>   psql -U postgres -d \$DB_DATABASE -c \"REASSIGN OWNED BY old_owner TO \$DB_USERNAME;\""
    exit 1
fi

# First-deploy seeding (one-click install)
if [ "$RUN_SEED_ON_FIRST_DEPLOY" = "true" ]; then
    echo "==> Running database seeder..."
    php artisan db:seed --force --no-interaction 2>/dev/null || true
fi

# Publish Livewire assets
php artisan livewire:publish --assets 2>/dev/null || true

echo "==> El Captain ready. Starting services..."

exec "$@"
