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

APP_DIR="${1:-$(pwd)}"
cd "$APP_DIR"

if [[ ! -f artisan || ! -f composer.json ]]; then
  echo "ERROR: run this script from the Laravel project root." >&2
  exit 1
fi

required_extensions=(bcmath ctype curl dom fileinfo json mbstring openssl pdo_mysql tokenizer xml)
for extension in "${required_extensions[@]}"; do
  php -r "exit(extension_loaded('$extension') ? 0 : 1);" || { echo "ERROR: missing PHP extension: $extension" >&2; exit 1; }
done

php artisan down --retry=30 || true
trap 'php artisan up >/dev/null 2>&1 || true' EXIT

if command -v composer >/dev/null 2>&1; then
  composer install --no-dev --prefer-dist --no-interaction --optimize-autoloader
elif [[ ! -f vendor/autoload.php ]]; then
  echo "ERROR: Composer is unavailable and vendor/ was not uploaded." >&2
  exit 1
fi

if [[ ! -f .env ]]; then
  cp deploy/staging.env.example .env
  echo "ERROR: .env was created from the template. Fill database credentials, then rerun." >&2
  exit 1
fi

if grep -q 'CHANGE_ME_' .env; then
  echo "ERROR: replace every CHANGE_ME_ value in .env before deployment." >&2
  exit 1
fi

if grep -q '^APP_KEY=$' .env; then
  php artisan key:generate --force
fi

mkdir -p storage/app/private storage/app/public storage/framework/cache/data storage/framework/sessions storage/framework/views storage/logs bootstrap/cache
chmod -R ug+rwX storage bootstrap/cache

php artisan optimize:clear
php artisan migrate --force
php artisan storage:link || true
php artisan optimize
php artisan queue:restart || true
php artisan up
trap - EXIT

php artisan about --only=environment,cache,drivers
echo "Deployment completed. Check: https://ezzgold.linkkps.com/health/ready"
