#!/bin/bash
set -u

# ---------------------------------------------------------------------------
# Config
# ---------------------------------------------------------------------------
threshold=${1:-30}
AUR_REPO="aur-local"
# stock kernel package -> your custom build of it. Add or remove entries freely.
declare -A KERNELS=(
    [linux]="linux-custom"
    [linux-lts]="linux-lts-custom"
    [linux-zen]="linux-zen-custom"
)
state_dir="${XDG_STATE_HOME:-$HOME/.local/state}/update-notify"

[[ $threshold =~ ^[0-9]+$ ]] || { echo "Threshold must be a number" >&2; exit 1; }
threshold=$((10#$threshold))  # force base 10, so e.g. "08" isn't read as octal
mkdir -p "$state_dir"

# notify-send from cron/systemd needs the session bus address
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=/run/user/$(id -u)/bus}"

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

# Send a notification only if its body changed since last time for this key.
notify_once() {
    local key=$1 title=$2 body=$3
    local file="$state_dir/$key"
    if [[ -f $file && $(<"$file") == "$body" ]]; then
        return 0
    fi
    notify-send "$title" "$body" && printf '%s' "$body" > "$file"
}

# Forget a key so the next occurrence notifies again.
clear_state() {
    rm -f "$state_dir/$1"
}

# If $1 has a pending update, print its new version and return 0.
# checkupdates lines look like: "pkgname oldver -> newver"
pending_version() {
    local pkg=$1 item new
    for item in "${arch_list[@]}"; do
        if [[ $item == "$pkg "* ]]; then
            read -r _ _ _ new <<< "$item"
            printf '%s\n' "$new"
            return 0
        fi
    done
    return 1
}

# Newest known version of $1: the pending version if an update is queued,
# otherwise the installed version. Returns 1 if the package isn't installed.
latest_version() {
    local pkg=$1 ver
    if ver=$(pending_version "$pkg"); then
        printf '%s\n' "$ver"
    elif ver=$(pacman -Q "$pkg" 2>/dev/null); then
        printf '%s\n' "${ver#* }"
    else
        return 1
    fi
}

# ---------------------------------------------------------------------------
# Gather updates
# ---------------------------------------------------------------------------

# Fetch checkupdates once. Exit codes: 0 = updates, 2 = none, 1 = error.
checkupdates_out=$(checkupdates 2>/dev/null)
checkupdates_rc=$?
if (( checkupdates_rc == 1 )); then
    # Bail out without touching the state, so the next good run doesn't re-notify
    echo "checkupdates failed (network or sync problem?)" >&2
    exit 1
fi

arch_list=()
if [[ -n $checkupdates_out ]]; then
    mapfile -t arch_list <<< "$checkupdates_out"
fi
arch_updates=${#arch_list[@]}

aur_updates=0
if command -v aur >/dev/null 2>&1; then
    if aur_out=$(aur repo -u -d "$AUR_REPO"); then
        [[ -n $aur_out ]] && aur_updates=$(wc -l <<< "$aur_out")
    else
        echo "aur repo -u failed, AUR updates not counted" >&2
    fi
fi
updates=$((arch_updates + aur_updates))

# ---------------------------------------------------------------------------
# Kernel check: the stock kernel updated, but your custom build didn't
# ---------------------------------------------------------------------------
kernel_lines=()
for stock_pkg in "${!KERNELS[@]}"; do
    custom_pkg=${KERNELS[$stock_pkg]}

    # Skip kernels where either package isn't installed
    if ! stock_ver=$(latest_version "$stock_pkg") || ! custom_ver=$(latest_version "$custom_pkg"); then
        continue
    fi

    # Flag the kernel while the stock one is newer than the newest custom build
    # (installed, or already built into your repo but not yet installed).
    # pkgrel is ignored: a stock packaging-only bump doesn't need a rebuild.
    if (( $(vercmp "${stock_ver%-*}" "${custom_ver%-*}") > 0 )); then
        kernel_lines+=("Rebuild $custom_pkg ($stock_pkg $stock_ver)")
    fi
done

# ---------------------------------------------------------------------------
# Build a single notification
#   - kernel rebuild lines are always included
#   - update counts and reminders only when the threshold is reached
# ---------------------------------------------------------------------------
over_threshold=0
(( updates >= threshold )) && over_threshold=1

parts=()
if (( over_threshold )); then
    parts+=("Arch: $arch_updates, AUR: $aur_updates")
fi
parts+=("${kernel_lines[@]}")

if (( over_threshold )); then
    reminders=()

    # Always remind about git packages if git-monitor is installed
    if command -v git-monitor >/dev/null 2>&1; then
        reminders+=("git-monitor")
    fi

    # Firmware: only mention it when updates actually exist.
    # fwupdmgr get-updates exits 0 when updates are available, 2 when there are none.
    # --no-metadata-check avoids prompting/refreshing; the fwupd-refresh timer keeps metadata fresh.
    if command -v fwupdmgr >/dev/null 2>&1; then
        if timeout 30 fwupdmgr get-updates --no-metadata-check </dev/null >/dev/null 2>&1; then
            reminders+=("fwupdmgr (firmware updates available)")
        fi
    fi

    if (( ${#reminders[@]} )); then
        printf -v list '%s, ' "${reminders[@]}"
        parts+=("Also check: ${list%, }")
    fi
fi

if (( ${#parts[@]} )); then
    title="Updates available"
    (( over_threshold )) || title="Kernel update available"
    printf -v body '%s\n' "${parts[@]}"
    notify_once "updates" "$title" "${body%$'\n'}"
else
    clear_state "updates"
fi
