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

# ==============================================================================
# irpf_certificados worker wrapper
# - Carga variables sensibles desde /etc/irpf_certificados/worker.env (chmod 600)
# - Evita ejecuciones solapadas con flock
# - Loguea inicio/fin y errores con timestamps
# ==============================================================================

APP_DIR="/var/www/desarrollo/public_html/apps/irpf_certificados"
PHP_BIN="/usr/bin/php"
WORKER_SCRIPT="worker/process_jobs.php"

LOG="/var/log/irpf_certificados_worker.log"
LOCK="/var/lock/irpf_certificados_worker.lock"

log() {
  echo "[WRAPPER] $(date '+%F %T') $*" >> "$LOG"
}

on_error() {
  local exit_code=$?
  log "ERROR en línea ${BASH_LINENO[0]} (exit=${exit_code})"
  exit "$exit_code"
}
trap on_error ERR

# --- Cargar entorno (secrets fuera del script) --------------------------------
ENV_FILE="/etc/irpf_certificados/worker.env"
if [[ -r "$ENV_FILE" ]]; then
  # shellcheck disable=SC1090
  set -a
  source "$ENV_FILE"
  set +a
else
  log "ERROR: no puedo leer $ENV_FILE (¿existe? ¿permisos 600?)"
  exit 1
fi

# --- Validaciones básicas ------------------------------------------------------
if [[ ! -x "$PHP_BIN" ]]; then
  log "ERROR: PHP no ejecutable en $PHP_BIN"
  exit 1
fi

if [[ ! -d "$APP_DIR" ]]; then
  log "ERROR: APP_DIR no existe: $APP_DIR"
  exit 1
fi

# --- Evitar solape de ejecuciones ---------------------------------------------
exec 200>"$LOCK"
if ! flock -n 200; then
  log "SKIP: ya hay una ejecución en curso (lock: $LOCK)"
  exit 0
fi

log "inicio"

cd "$APP_DIR"
# (Opcional) DEBUG=1 para chequear variables sin exponer passwords completas
if [[ "${DEBUG:-0}" == "1" ]]; then
  "$PHP_BIN" -r '
    echo "[ENVCHK] HOST=". (getenv("SMTP_HOST") ?: "NULL").PHP_EOL;
    echo "[ENVCHK] USER=". (getenv("SMTP_USER") ?: "NULL").PHP_EOL;
    echo "[ENVCHK] PASS=". (getenv("SMTP_PASS") ? "[SET len=".strlen(getenv("SMTP_PASS"))."]" : "NULL").PHP_EOL;
    echo "[ENVCHK] PORT=". (getenv("SMTP_PORT") ?: "NULL").PHP_EOL;
    echo "[ENVCHK] FROM=". (getenv("MAIL_NOREPLY_EMAIL") ?: "NULL").PHP_EOL;
    echo "[ENVCHK] FROM_NAME=". (getenv("MAIL_NOREPLY_NAME") ?: "NULL").PHP_EOL;
  ' >> "$LOG" 2>&1
fi

"$PHP_BIN" "$WORKER_SCRIPT" >> "$LOG" 2>&1
log "fin (exit=0)"
