#!/bin/bash
#=========================================#
# Simple update notifier (DNF) v0.3.8     #
#=========================================#
CONFIG=/var/tmp/.simple-notifier
if ! test -d $CONFIG; then
mkdir -p $CONFIG
chmod 0777 $CONFIG
touch $CONFIG/update_pkgs
touch $CONFIG/up2date
chmod 0777 $CONFIG/update_pkgs
chmod 0777 $CONFIG/up2date
fi

# File paths
UPDATE_COUNT_FILE="/var/tmp/.simple-notifier/num_updates"
UPDATE_LIST_FILE="/var/tmp/.simple-notifier/show_info"
TMP_COUNT_FILE="/var/tmp/.simple-notifier/tmp_num_updates"
TMP_LIST_FILE="/var/tmp/.simple-notifier/tmp_show_info"


# Initial check after a short delay (network may need time)
sleep 30

# Function to check updates
run_check() {
    dnf -q check-update --refresh 2>/dev/null | awk -v tmp_count="$TMP_COUNT_FILE" -v tmp_list="$TMP_LIST_FILE" '
    BEGIN {
        c=0
        in_obsolete=0
        written=0
        delete found_packages
    }

    /^Obsoleting/ {in_obsolete=1; next}

    !in_obsolete && NF > 1 && /^[[:alnum:]]/ {
        if (!($1 in found_packages)) {
            found_packages[$1]
            if (!written) {
                print > tmp_list
                written=1
            } else {
                print >> tmp_list
            }
            c++
        }
        next
    }

    in_obsolete && NF > 2 && /^[[:alnum:]]/ {
        if ($3 != "<unknown>" && !($1 in found_packages)) {
            found_packages[$1]
            if (!written) {
                print > tmp_list
                written=1
            } else {
                print >> tmp_list
            }
            c++
        }
    }

    END {
        print c > tmp_count
    }'
    
    # Move temporary files to their final destination
    mv -f "$TMP_COUNT_FILE" "$UPDATE_COUNT_FILE"
    mv -f "$TMP_LIST_FILE" "$UPDATE_LIST_FILE"
    chmod 0777 "$UPDATE_COUNT_FILE" "$UPDATE_LIST_FILE"
    # Remove junk files
    rm -f $CONFIG/tmp_*  

 }

run_check

# Periodic checks every 120 minutes
while true; do
    sleep 120m
    run_check
done

