#!/bin/bash
# ============================================================
# weekly_report.sh — Rapport hebdomadaire sécurité / Citronze
# Cron : 1x/semaine (ex: lundi 8h)
# ============================================================

REPORT_DIR="/homez.432/citronze/scan_reports"
ALERT_TO="miran@citronzebre.fr"
ALERT_FROM="nepasrepondre@citronzebre.fr"
DATE_HUMAN=$(date '+%d/%m/%Y %H:%M')
WEEK=$(date '+%V')
YEAR=$(date '+%Y')

# --- Agréger les logs de la semaine ---
TOTAL_OK=$(grep -c "OK — aucun suspect" "$REPORT_DIR/monitor.log" 2>/dev/null || echo 0)
TOTAL_ALERTS=$(grep -c "ALERTE" "$REPORT_DIR/monitor.log" 2>/dev/null || echo 0)

# Rapports avec suspects cette semaine
SUSPECT_REPORTS=$(find "$REPORT_DIR" -name "monitor_*.txt" -mtime -7 -exec grep -l "suspect\|⚠\|🔴" {} \; 2>/dev/null)

# Construire le corps du mail
BODY="RAPPORT HEBDOMADAIRE SÉCURITÉ — Semaine $WEEK/$YEAR
Généré le $DATE_HUMAN
============================================

RÉSUMÉ
------
Scans OK (aucun suspect)  : $TOTAL_OK
Scans avec alertes         : $TOTAL_ALERTS

"

if [ -n "$SUSPECT_REPORTS" ]; then
    BODY+="DÉTAIL DES ALERTES CETTE SEMAINE
---------------------------------
"
    for REPORT in $SUSPECT_REPORTS; do
        BODY+="$(cat "$REPORT")"
        BODY+="\n\n"
    done
else
    BODY+="✅ Aucune alerte cette semaine."
fi

BODY+="
============================================
Log complet : $REPORT_DIR/monitor.log"

# Sortie stdout — OVH envoie par mail automatiquement
echo "$BODY"
echo "[$(date '+%d/%m/%Y %H:%M')] Rapport hebdo généré" >> "$REPORT_DIR/monitor.log"
