#!/usr/bin/env bash
set -euo pipefail

cd /var/www/html

if [[ -z "${APP_KEY:-}" ]]; then
  echo "ERROR: APP_KEY is empty. Set a secure Laravel APP_KEY in .env." >&2
  exit 1
fi

mkdir -p storage/framework/cache/data storage/framework/sessions storage/framework/views storage/logs bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache

if [[ "${DB_CONNECTION:-mysql}" == "mysql" ]]; then
  echo "Waiting for MySQL at ${DB_HOST:-mysql}:${DB_PORT:-3306}..."
  php -r '
    $host=getenv("DB_HOST") ?: "mysql";
    $port=getenv("DB_PORT") ?: "3306";
    $db=getenv("DB_DATABASE") ?: "";
    $user=getenv("DB_USERNAME") ?: "";
    $pass=getenv("DB_PASSWORD") ?: "";
    $deadline=time()+90;
    do {
      try {
        new PDO("mysql:host={$host};port={$port};dbname={$db}",$user,$pass,[PDO::ATTR_TIMEOUT=>3]);
        exit(0);
      } catch (Throwable $e) {
        if (time()>=$deadline) { fwrite(STDERR,"MySQL connection timed out: ".$e->getMessage().PHP_EOL); exit(1); }
        sleep(2);
      }
    } while (true);
  '
fi

exec "$@"
