#!/usr/bin/env bash

usage() {
	cat <<HELP

get-updates [option]

--notify   send a notification with available packages
-h,--help  print this page and exit

HELP
	exit 0
}

header() {
	echo "============="
}

updates_output() {
	notify=$1
	if [[ -n $updates_arch ]]; then
		header
		echo "ARCH: $(echo "$updates_arch" | wc -l)"
		header
		[[ -z $notify ]] && echo "$updates_arch"
	fi
	if [[ -n $updates_aur ]]; then
		header
		echo "AUR: $(echo "$updates_aur" | wc -l)"
		header
		[[ -z $notify ]] && echo "$updates_aur"
	fi
	echo
}

update_system() {
	echo
	read -r -p "Would you like to update? (y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
	paru -Syu
}

for opt in "$@"; do
	case $opt in
	-h | --help)
		usage
		;;
	--notify)
		notify=1
		shift
		;;
	-*)
		echo "Invalid option: $opt"
		usage
		;;
	esac
done

echo "fetching updates..."
echo

updates_arch="$(checkupdates 2>/dev/null | awk '{print $1}' | column)"
updates_aur="$(paru -Qua 2>/dev/null | awk '{print $1}' | column)"
updates_info="$(updates_output "$notify")"

if [[ -z $updates_info ]]; then
	echo "system up to date"
	exit 0
fi

if [[ -n $notify ]]; then
	notify-send -w "System Updates Available!" "$updates_info" &
else
	echo "System Updates Available!"
	echo "$updates_info"
	update_system
fi