#!/usr/bin/env bash
# Diagnose Laravel 503 on cPanel — run from the app root (where artisan lives)
set -uo pipefail

APP_DIR="${1:-${PWD}}"
cd "${APP_DIR}"

PHP_BIN="${PHP_BIN:-php}"

echo "============================================"
echo " Laravel 503 diagnostic"
echo " App: ${APP_DIR}"
echo " Date: $(date)"
echo "============================================"
echo ""

section() { echo ""; echo "== $1 =="; }

section "Document root check"
if [[ -f public/index.php ]]; then
  echo "public/index.php: OK"
else
  echo "public/index.php: MISSING — wrong folder?"
fi

section "Maintenance files"
for f in storage/framework/down storage/framework/maintenance.php; do
  if [[ -f "$f" ]]; then
    echo "FOUND (503 cause): $f"
    ls -la "$f"
  else
    echo "absent: $f"
  fi
done

section ".env"
if [[ -f .env ]]; then
  echo ".env: present"
  grep -E '^APP_(ENV|DEBUG|URL|KEY)=' .env 2>/dev/null | sed 's/APP_KEY=.*/APP_KEY=***hidden***/'
else
  echo ".env: MISSING — copy from backup or .env.example"
fi

section "Permissions (must be writable by web server)"
for d in bootstrap/cache storage storage/framework storage/framework/cache storage/framework/cache/data storage/framework/sessions storage/framework/views storage/logs; do
  if [[ -d "$d" ]]; then
    perms=$(stat -c '%a %U %G' "$d" 2>/dev/null || ls -ld "$d")
    if [[ -w "$d" ]]; then
      echo "OK (SSH writable): $d — $perms"
    else
      echo "NOT writable (SSH): $d — $perms"
    fi
  else
    echo "MISSING: $d"
  fi
done

section "bootstrap/cache contents"
ls -la bootstrap/cache/ 2>/dev/null || echo "(empty or missing)"

section "Artisan"
if [[ -f artisan ]]; then
  "${PHP_BIN}" artisan --version 2>&1 || echo "artisan failed"
  echo ""
  "${PHP_BIN}" artisan about 2>&1 | head -20 || true
else
  echo "artisan not found"
fi

section "Recent errors (laravel.log)"
if [[ -f storage/logs/laravel.log ]]; then
  tail -30 storage/logs/laravel.log
else
  echo "No laravel.log yet"
fi

section "Health route hint"
echo "After fixing permissions, test in browser:"
echo "  https://test.duiclick.com/up"
echo ""
echo "Quick fix to try:"
echo "  cd ${APP_DIR}"
echo "  rm -f storage/framework/down storage/framework/maintenance.php"
echo "  mkdir -p bootstrap/cache storage/framework/{cache/data,sessions,views} storage/logs"
echo "  chmod -R 777 storage bootstrap/cache"
echo "  ${PHP_BIN} artisan config:clear && ${PHP_BIN} artisan cache:clear"
echo "  Then: cPanel MultiPHP Manager -> Reset OPcache"
