#!/bin/bash
# Раз в несколько часов: если pacman видит обновления — показываем уведомление.
# Если среди них zaryv-settings с новым VERSION в /etc/zaryv-release —
# это выпуск системы, не обычные пакеты.
# Клик (действие default) открывает Магазин Zaryv на вкладке обновлений.

set -u

if ! command -v checkupdates >/dev/null 2>&1; then
    exit 0
fi

updates="$(checkupdates 2>/dev/null)" || status=$?
status=${status:-0}
# checkupdates: 0 — пусто, 2 — есть обновления, 1 — ошибка сети или базы.
if [[ "$status" -ne 2 || -z "${updates}" ]]; then
    exit 0
fi

count="$(printf '%s\n' "$updates" | grep -c . || true)"
title="Доступны обновления"
body="Пакеты: ${count}. Нажмите, чтобы открыть Магазин Zaryv."

current=""
if [[ -f /etc/zaryv-release ]]; then
    # shellcheck disable=SC1091
    current="$(awk -F= '/^VERSION=/{print $2; exit}' /etc/zaryv-release)"
fi

if printf '%s\n' "$updates" | awk '{print $1}' | grep -qx 'zaryv-settings'; then
    tmp="$(mktemp -d)"
    db="$(mktemp -d)"
    if pacman -Syw --dbpath "$db" --cachedir "$tmp" --noconfirm zaryv-settings >/dev/null 2>&1; then
        pkg="$(find "$tmp" -name 'zaryv-settings-*.pkg.tar.zst' | head -n 1)"
        if [[ -n "${pkg}" ]]; then
            newver="$(bsdtar -xOf "$pkg" etc/zaryv-release 2>/dev/null | awk -F= '/^VERSION=/{print $2; exit}')"
            if [[ -n "${newver}" && "${newver}" != "${current}" ]]; then
                title="Доступна Zaryv OS ${newver}"
                notes="$(bsdtar -xOf "$pkg" usr/share/zaryv/CHANGELOG.md 2>/dev/null | awk '
                    /^## / { n++; if (n > 1) exit }
                    n >= 1 { print }
                ' | head -n 8)"
                if [[ -n "${notes}" ]]; then
                    body="${notes}"
                fi
            fi
        fi
    fi
    rm -rf "$tmp" "$db"
fi

open_store() {
    if command -v plasma-discover >/dev/null 2>&1; then
        exec plasma-discover --mode update
    fi
    if command -v discover >/dev/null 2>&1; then
        exec discover --mode update
    fi
    exit 0
}

if ! command -v notify-send >/dev/null 2>&1; then
    printf '%s\n%s\n' "$title" "$body" >&2
    exit 0
fi

action="$(notify-send \
    --app-name="Zaryv OS" \
    --icon=system-software-update \
    --action=default="Открыть" \
    --wait \
    "$title" \
    "$body" 2>/dev/null || true)"

if [[ "$action" == "default" ]]; then
    open_store
fi
exit 0
