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

BRANCH="${1:-main}"
APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

cd "$APP_DIR"

echo "[deploy] Branch: $BRANCH"
echo "[deploy] App dir: $APP_DIR"

echo "[deploy] Fetching latest code..."
git fetch origin

echo "[deploy] Resetting working tree to origin/$BRANCH..."
git reset --hard "origin/$BRANCH"

echo "[deploy] Installing PHP dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction --prefer-dist

echo "[deploy] Running migrations..."
php artisan migrate --force

echo "[deploy] Ensuring public storage symlink..."
# public/storage must be a SYMLINK, never a real dir. (It used to be tracked in
# git, so every reset recreated it as a folder and clobbered the link.)
if [ ! -L public/storage ]; then
  rm -rf public/storage
  php artisan storage:link
fi

echo "[deploy] Refreshing caches..."
# NOTE: never run `route:cache` / `optimize` — it breaks the host-based routing.
php artisan optimize:clear
php artisan config:cache
php artisan view:cache

echo "[deploy] Reciclando PHP para que suelte el bytecode viejo..."
# El caché de OPcache del proceso web es OTRO distinto del de la CLI: `artisan
# optimize:clear` no lo toca. Si el servidor lleva `opcache.validate_timestamps=0`
# (afinado habitual en producción), tras un despliegue se sigue sirviendo el
# código anterior hasta que el proceso recicla — y eso se ve como «media web
# nueva y media vieja», que es exactamente el síntoma que se revisó el 26-07.
# Best-effort: si no hay permiso, avisa en vez de fallar el despliegue.
RECICLADO=no
for SERVICIO in php8.4-fpm php8.3-fpm php8.2-fpm php-fpm apache2; do
  if systemctl list-units --type=service --all 2>/dev/null | grep -q "$SERVICIO"; then
    if sudo -n systemctl reload "$SERVICIO" 2>/dev/null; then
      echo "[deploy]   reload de $SERVICIO hecho"
      RECICLADO=si
      break
    fi
  fi
done
if [ "$RECICLADO" = "no" ]; then
  echo "[deploy]   ⚠ no se pudo reciclar PHP. Si la web sale a medias, recarga a mano:"
  echo "[deploy]     sudo systemctl reload php8.4-fpm   (o apache2, según el montaje)"
fi

echo "[deploy] Restarting queue workers (no-op if none running)..."
php artisan queue:restart

echo "[deploy] Done."
