#!/bin/sh

case "$(readlink -f /sbin/init)" in
	*systemd*) export DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus ;;
esac

ping -q -c 1 example.org > /dev/null || exit


pgrepoutput="$(pgrep -a X\(org\|wayland\))"
displays="$(echo "$pgrepoutput" | grep -wo "[0-9]*:[0-9]\+" | sort -u)"
notify() {
	[ -n "$pgrepoutput" ] && for x in ${displays:-:0}; do
		export DISPLAY=$x
		notify-send --app-name="auto-update" "$1" "$2"
	done ;
}

notify " Repository Sync" "Checking for package updates..."

sudo pacman -Syyuw --noconfirm || notify " An error occured" "Error downloading updates.
Check your internet connection, if pacman is already running, or run update manually to see errors."

if pacman -Qu | grep -v "\[ignored\]"
then
	checkupdates 2> /dev/null > ~/.cache/pacman_updates
	notify " Repository Sync" "$(pacman -Qu | grep -v "\[ignored\]" | wc -l) Updates available. Click statusbar icon (  ) for update."
else
	notify " Repository Sync"  "Sync complete. No new packages for update."
fi

kill -49 "$(pidof dwmblocks)"
