#!/bin/bash
# slk-notify-daemon.sh
# Waits for updates_pending flag and notifies the user.

FLAG_FILE="/var/cache/slk-changelog/updates_pending"
LOCK_FILE="/tmp/slk-notify.lock"

# --- Lock: only one instance allowed ---
exec 9>"${LOCK_FILE}"
flock -n 9 || { echo "Already running. Exiting."; exit 1; }

# --- Notification function (non-blocking) ---
send_notification() {
    if command -v kdialog &>/dev/null; then
        kdialog --icon system-software-update \
                --title "Slackpkg Update Checker" \
                --msgbox "Slackware system updates found!" &
    elif command -v zenity &>/dev/null; then
        zenity --info \
               --title="Slackpkg Update Checker" \
               --text="Slackware system updates found!" &
    else
        notify-send \
            --icon=system-software-update \
            "Slackpkg Update Checker" \
            "Slackware system updates found!"
    fi
}

# --- Wait for session to stabilize ---
sleep 150

# --- Main polling loop ---
while true; do
    if [[ -f "${FLAG_FILE}" ]]; then
        rm -f "${FLAG_FILE}"
        send_notification
    fi
    sleep 120
done
