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

# ==== Ajuste SE necessário ====
PROJECT_ROOT="/home/gopangratest/public_html/api-goptest-angra"
PHP_BIN="/usr/local/bin/php"
COMPOSER_BIN="/opt/cpanel/composer/bin/composer"
# ==============================

# Sempre execute a partir da raiz do projeto (o webhook roda em public/hooks)
cd "$PROJECT_ROOT"

echo "[entrypoint] CWD: $(pwd)"
echo "[entrypoint] PHP: $($PHP_BIN -v | head -n1)"
echo "[entrypoint] Composer: $($COMPOSER_BIN --version)"

# Garante pastas usadas
mkdir -p storage/api-docs public/docs storage/framework/views bootstrap/cache

# Gera Swagger (não quebra se falhar) e copia JSONs se existirem
set +e
$PHP_BIN artisan l5-swagger:generate --ansi
set -e

# Copia somente se existir JSON
shopt -s nullglob
swagger_json=(storage/api-docs/*.json)
if (( ${#swagger_json[@]} )); then
  cp storage/api-docs/*.json public/docs/
  echo "[entrypoint] Swagger copiado para public/docs/"
else
  echo "[entrypoint] Nenhum JSON Swagger encontrado em storage/api-docs/"
fi
shopt -u nullglob

# Dependências PHP (se ainda não houver vendor/)
if [ ! -f vendor/autoload.php ]; then
  echo "[entrypoint] Instalando dependências PHP..."
  "$COMPOSER_BIN" install
  "$COMPOSER_BIN" run-script post-autoload-dump || true
fi

# Dependências JS (se houver package.json e faltar node_modules)
if [ -f package.json ] && [ ! -d node_modules ]; then
  echo "[entrypoint] Instalando dependências JS…"
  if [ -f package-lock.json ]; then
    npm ci
  else
    npm install --ignore-scripts
  fi
  # Se houver build script
  if npm run | grep -qE ' build '; then
    npm run build
  fi
fi

# Permissões (use o próprio usuário do cPanel)
chown -R gopangratest:gopangratest storage public/docs bootstrap/cache || true
chmod -R 775 storage public/docs bootstrap/cache || true

# (Opcional) Migrations automáticas: habilite definindo RUN_MIGRATIONS=1 no .env
if [ "${RUN_MIGRATIONS:-0}" = "1" ]; then
  echo "[entrypoint] Rodando migrations..."
  $PHP_BIN artisan migrate --force
else
  echo "[entrypoint] Migrations puladas (RUN_MIGRATIONS != 1)"
fi

# Limpa e recompila caches do Laravel
$PHP_BIN artisan config:clear
$PHP_BIN artisan cache:clear
$PHP_BIN artisan route:clear
$PHP_BIN artisan view:clear

$PHP_BIN artisan config:cache
$PHP_BIN artisan route:cache
$PHP_BIN artisan view:cache

echo "[entrypoint] Finalizado com sucesso."
