#!/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
chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache

# Build .env from Docker env vars (CapRover passes them as container env)
: > .env
env | grep -E "^(APP_|DB_|LOG_|SESSION_|CACHE_|QUEUE_|FILESYSTEM_|BROADCAST_|MAIL_|TRUSTED_|BCRYPT_|PLATFORM_|ADMIN_|ACADEMY_|RUN_|WHATSAPP_|MESSAGING_)" | 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
php artisan migrate --force --no-interaction

# 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 "$@"
