#!/bin/sh
set -e

cd /var/www/html

wait_for_database() {
    if [ -z "$DB_HOST" ] || [ -z "$DB_DATABASE" ]; then
        return 0
    fi

    echo "Waiting for database at ${DB_HOST}:${DB_PORT:-3306}..."

    until php -r "
        \$host = getenv('DB_HOST') ?: '127.0.0.1';
        \$port = getenv('DB_PORT') ?: '3306';
        \$database = getenv('DB_DATABASE') ?: '';
        \$username = getenv('DB_USERNAME') ?: 'root';
        \$password = getenv('DB_PASSWORD') ?: '';
        try {
            new PDO(
                \"mysql:host={\$host};port={\$port};dbname={\$database}\",
                \$username,
                \$password,
                [PDO::ATTR_TIMEOUT => 3]
            );
            exit(0);
        } catch (Throwable \$e) {
            exit(1);
        }
    " 2>/dev/null; do
        sleep 2
    done

    echo "Database is ready."
}

ensure_dependencies() {
    if [ ! -f vendor/autoload.php ] && command -v composer >/dev/null 2>&1; then
        echo "Installing PHP dependencies..."
        composer install --no-interaction --prefer-dist
    fi
}

prepare_application() {
    if [ ! -f .env ] && [ -f .env.example ]; then
        cp .env.example .env
    fi

    if [ ! -f vendor/autoload.php ]; then
        echo "Skipping Laravel bootstrap until Composer dependencies are installed."
        return 0
    fi

    if [ -z "$APP_KEY" ]; then
        php artisan key:generate --force --no-interaction
    fi

    php artisan storage:link --force --no-interaction 2>/dev/null || true
    php artisan migrate --force --no-interaction

    if [ "$APP_ENV" = "production" ]; then
        php artisan config:cache --no-interaction
        php artisan route:cache --no-interaction
        php artisan view:cache --no-interaction
    fi

    chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || true
}

wait_for_database
ensure_dependencies
prepare_application

exec "$@"