#!/bin/bash
# ansipa-check-scans.sh — analyse client scan logs and create alert files.
# Runs hourly via /etc/cron.d/ansipa-check-scans (installed by ansipa-smb-setup.sh).
#
# Input:  /data/scan-results/archive/<hostname>/<YYYY-MM-DD>.log
# Output: /data/scan-results/alerts/<hostname>/<YYYY-MM-DD>.alert
#           (created only when concerning patterns are found; client deletes to acknowledge)

SCAN_BASE="/data/scan-results"
ARCHIVE_DIR="$SCAN_BASE/archive"
ALERT_DIR="$SCAN_BASE/alerts"
LOG=/var/log/ansipa-check-scans.log

log() { printf '[%s] [ansipa-check-scans] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" >> "$LOG"; }

# Patterns that indicate a concerning scan result (case-insensitive).
CONCERN_PATTERNS=(
    "FOUND"             # ClamAV: virus or trojan found
    "Infected files: [^0]"  # ClamAV summary with non-zero count
    "Warning:"          # rkhunter warning
    "Possible rootkit"  # rkhunter
    "INFECTED"          # generic
    "Suspicious file"   # chkrootkit
    "INFECTED SOURCE"   # chkrootkit
)

shopt -s nullglob

for HOST_DIR in "$ARCHIVE_DIR"/*/; do
    [[ -d "$HOST_DIR" ]] || continue
    HOSTNAME=$(basename "$HOST_DIR")
    mkdir -p "$ALERT_DIR/$HOSTNAME"

    for SCAN_LOG in "$HOST_DIR"*.log; do
        [[ -f "$SCAN_LOG" ]] || continue
        LOG_DATE=$(basename "$SCAN_LOG" .log)
        ALERT_FILE="$ALERT_DIR/$HOSTNAME/$LOG_DATE.alert"

        # Skip if we already generated an alert for this log.
        [[ -f "$ALERT_FILE" ]] && continue

        FINDINGS=()
        for PATTERN in "${CONCERN_PATTERNS[@]}"; do
            while IFS= read -r LINE; do
                FINDINGS+=("$LINE")
            done < <(grep -iE "$PATTERN" "$SCAN_LOG" 2>/dev/null || true)
        done

        # Deduplicate.
        mapfile -t FINDINGS < <(printf '%s\n' "${FINDINGS[@]}" | sort -u)

        if [[ ${#FINDINGS[@]} -gt 0 ]]; then
            log "ALERT: $HOSTNAME / $LOG_DATE — ${#FINDINGS[@]} finding(s)"
            {
                printf '=== Ansipa Security Alert ===\n'
                printf 'Host:     %s\n' "$HOSTNAME"
                printf 'Scan:     %s\n' "$LOG_DATE"
                printf 'Findings: %d\n' "${#FINDINGS[@]}"
                printf '\nConcerning lines:\n'
                printf '  %s\n' "${FINDINGS[@]}"
                printf '\nFull log: %s\n' "$SCAN_LOG"
                printf '\nTo acknowledge: delete this file on the client.\n'
                printf '=== Generated: %s ===\n' "$(date)"
            } > "$ALERT_FILE"
        else
            log "OK: $HOSTNAME / $LOG_DATE — clean"
        fi
    done
done

log "Check complete."
