#!/usr/bin/env bash
#
# update-project.sh — git pull + clear caches en el clone de un tenant.
#
# Idempotente y no destructivo: solo toca código + caches. NO toca:
#   - la DB del tenant
#   - los settings (sobreescritos por DB de todas formas)
#   - storage/ ni public/uploads/
#
# Llamado por el webhook bewpro-webhook.py cuando recibe POST /update.
#
# Uso:
#   update-project.sh --user=cpanel_user [--branch=cd-system] [--dry-run]
#
# Detecta automáticamente el VPS (cPanel vs HestiaCP) por el path del home
# y elige el directorio del clone correcto.
#
# Salida exit:
#   0 = OK (git pull aplicado o ya estaba al día)
#   1 = parametros inválidos
#   2 = clone directory no existe
#   3 = error de git
#   4 = error de cache clear

set -uo pipefail

USER=""
BRANCH="cd-system"
DRY_RUN=0

while [ $# -gt 0 ]; do
  case "$1" in
    --user=*)   USER="${1#*=}" ;;
    --branch=*) BRANCH="${1#*=}" ;;
    --dry-run)  DRY_RUN=1 ;;
    *) echo "Arg desconocido: $1" >&2; exit 1 ;;
  esac
  shift
done

if [ -z "$USER" ]; then
  echo "ERROR: --user es requerido" >&2
  exit 1
fi

# Resolver directorio del clone (cPanel vs HestiaCP)
CLONE_DIR=""
if [ -d "/home/$USER/public_html/git-files/$USER" ]; then
  # cPanel layout
  CLONE_DIR="/home/$USER/public_html/git-files/$USER"
elif [ -d "/home/$USER/web" ]; then
  # HestiaCP: hay que buscar el primer dominio (el principal)
  for DOMAIN_DIR in /home/$USER/web/*/public_html/git-files/$USER; do
    if [ -d "$DOMAIN_DIR" ]; then
      CLONE_DIR="$DOMAIN_DIR"
      break
    fi
  done
fi

if [ -z "$CLONE_DIR" ] || [ ! -d "$CLONE_DIR" ]; then
  echo "ERROR: clone directory no encontrado para user=$USER" >&2
  echo "  Probé: /home/$USER/public_html/git-files/$USER" >&2
  echo "  Probé: /home/$USER/web/*/public_html/git-files/$USER" >&2
  exit 2
fi

# Detectar binario PHP (cPanel suele tener /usr/local/bin/php, HestiaCP/Ubuntu /usr/bin/php)
PHP_BIN=""
for CANDIDATE in /usr/local/bin/php /usr/bin/php /usr/bin/php8.3 /usr/bin/php8.2 /usr/bin/php8.1; do
    if [ -x "$CANDIDATE" ]; then
        PHP_BIN="$CANDIDATE"
        break
    fi
done
if [ -z "$PHP_BIN" ]; then
    echo "WARN: no se encontró binario PHP — se omite cache clear"
fi

echo "════════════════════════════════════════════════════"
echo "  Update tenant: $USER"
echo "  Clone:  $CLONE_DIR"
echo "  Branch: $BRANCH"
echo "  PHP:    ${PHP_BIN:-NOT FOUND}"
echo "  DryRun: $DRY_RUN"
echo "════════════════════════════════════════════════════"

if [ "$DRY_RUN" -eq 1 ]; then
  echo "[DRY] No ejecuta nada."
  exit 0
fi

# Ejecutar git pull como el user (no como root)
echo "── git pull origin $BRANCH ──"
GIT_OUTPUT=$(su -s /bin/bash -c "cd '$CLONE_DIR' && git pull origin $BRANCH 2>&1" "$USER")
GIT_EXIT=$?
echo "$GIT_OUTPUT"

if [ $GIT_EXIT -ne 0 ]; then
  echo "ERROR: git pull falló (exit $GIT_EXIT)" >&2
  exit 3
fi

# Clear caches (view + config + route) — solo si encontramos binario PHP
if [ -n "$PHP_BIN" ]; then
  echo ""
  echo "── $PHP_BIN artisan view:clear / config:clear / route:clear ──"
  CACHE_OUTPUT=$(su -s /bin/bash -c "cd '$CLONE_DIR' && $PHP_BIN artisan view:clear 2>&1 && $PHP_BIN artisan config:clear 2>&1 && $PHP_BIN artisan route:clear 2>&1" "$USER")
  CACHE_EXIT=$?
  echo "$CACHE_OUTPUT"
  if [ $CACHE_EXIT -ne 0 ]; then
    echo "WARN: cache clear devolvió exit $CACHE_EXIT (puede ser cosmético)"
  fi
else
  echo ""
  echo "── cache clear SKIP: no se detectó binario PHP ──"
fi

echo ""
echo "✓ Update completo para $USER"
exit 0
