#!/usr/bin/env bash
# ansipa-scan-notify.sh — user-session scan alert notification daemon.
# Started automatically on login via /etc/profile.d/ansipa-notify.sh.
#
# Behaviour:
#   - Checks ~/administration/ for *.alert files every 10 minutes.
#   - Sends a desktop notification (notify-send) for any unacknowledged alerts.
#   - Re-notifies every 10 minutes as long as alert files remain.
#   - Deleting an alert file counts as acknowledgment — notifications stop.
#   - Exits when no alert files remain AND none have been seen this session,
#     but keeps running once any alert is ever found (to catch future ones).

ADMIN_DIR="$HOME/administration"
NOTIFY_INTERVAL=600   # 10 minutes
ICON="security-high"  # freedesktop icon name

notified_once=false

notify_alerts() {
    local alerts=() file count=0

    mapfile -t alerts < <(find "$ADMIN_DIR" -name "*.alert" 2>/dev/null | sort)
    count=${#alerts[@]}

    [[ $count -eq 0 ]] && return 0

    local title body
    if [[ $count -eq 1 ]]; then
        local name
        name=$(basename "${alerts[0]}" .alert)
        title="Security alert: $name"
        body="Check $ADMIN_DIR\nDelete the file to acknowledge."
    else
        title="$count unacknowledged security alerts"
        body="Check $ADMIN_DIR\nDelete files to acknowledge."
    fi

    notify-send -u critical -i "$ICON" -t 0 "$title" "$body" 2>/dev/null \
        || notify-send -u critical "$title" "$body" 2>/dev/null \
        || echo "[ansipa-notify] ALERT: $title — $body" >&2

    notified_once=true
}

mkdir -p "$ADMIN_DIR"

while true; do
    notify_alerts
    sleep "$NOTIFY_INTERVAL"
done
