#!/bin/sh

# Syncs repositories and downloads updates, meant to be run as a cronjob.

notify-send " Repository Sync" "Checking for package updates..."

askupgrade() {
    [ "$(notify-send -c updates --action=Yes=Yes --action=No=No " Repository Sync" "Updates available. Update now?")" = 'Yes' ] && $TERMINAL -e upgrades
}

confirmcheck() {
    notify-send " Repository Sync" "Sync complete. No new packages for update."
}

failcheck() {
    notify-send "Error downloading updates." "Check your internet connection, if $1 is already running, or run update manually to see errors."
}

if command -v pacman 1>/dev/null 2>&1; then
	sudo pacman -Syyuw --noconfirm || failcheck pacman
	if pacman -Qu | grep -v "\[ignored\]"; then
        askupgrade
	else
        confirmcheck
	fi
elif command -v apt 1>/dev/null 2>&1; then
	n=$(sudo apt upgrade -dy 2>/dev/null | grep -m1 '^[0-9]\+ upgraded,' | tr -cd '0-9' | cut -c1-2)
	if [ "$n" = '' ]; then
        failcheck apt
	elif [ "$n" = 00 ]; then
        confirmcheck
	else
        askupgrade
	fi
fi