#!/usr/bin/env bash
#
# NIS2 Agile — Supplier Questionnaire Cron (Fase 2)
# Wrapper sottile per scripts/supplier-questionnaire-runner.php.
#   - TZ=Europe/Rome (standard di progetto)
#   - flock in /tmp (no run sovrapposti; il runner è comunque idempotente)
#   - log su /var/log/nis2-supplier-cron.log
#
# Crontab root (06:00 Europe/Rome, fuori finestra DST 02:00-03:00):
#   0 6 * * * /var/www/nis2-agile/scripts/supplier-questionnaire-cron.sh
#
set -euo pipefail
export TZ=Europe/Rome

PHP_BIN="${PHP_BIN:-/usr/bin/php}"
RUNNER="/var/www/nis2-agile/scripts/supplier-questionnaire-runner.php"
LOG_FILE="/var/log/nis2-supplier-cron.log"
LOCK_FILE="/tmp/nis2-supplier-questionnaire-cron.lock"

mkdir -p "$(dirname "$LOG_FILE")" 2>/dev/null || true
touch "$LOG_FILE" 2>/dev/null || true

exec 9>"$LOCK_FILE"
if ! flock -n 9; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S %Z')] Lock attivo, run precedente in corso. Uscita." >> "$LOG_FILE"
    exit 0
fi

echo "[$(date '+%Y-%m-%d %H:%M:%S %Z')] --- avvio supplier-questionnaire-cron ---" >> "$LOG_FILE"
"$PHP_BIN" "$RUNNER" >> "$LOG_FILE" 2>&1
rc=$?
echo "[$(date '+%Y-%m-%d %H:%M:%S %Z')] --- fine (exit=$rc) ---" >> "$LOG_FILE"
exit "$rc"
