#!/bin/bash

set -e

UNAME=$(sh -c 'uname 2>/dev/null || echo Unknown')

. ~/.local/opt/script_utils/parse-package-managers-params.bash

if [ "${RUN[pacman]}" = "1" ]
then
	# Clear out orphans
	sudo pacman -Rns $(pacman -Qtdq)

	# Update arch packages
	sudo pacman -Syu

	# Update AUR packages
	aurfetch update-all -q
fi

if [ "${RUN[apt]}" = "1" ]
then
	# Clear out orphans
	sudo apt autoremove

	# Update apt packages
	sudo apt update
	sudo apt full-upgrade

	# Clear out orphans
	sudo apt autoremove
fi

if [ "${RUN[dnf]}" = "1" ]
then
	# Clear out orphans
	sudo dnf autoremove

	# Update dnf packages
	sudo dnf update --refresh

	# Clear out orphans
	sudo dnf autoremove
fi

if [ "${RUN[flatpak]}" = "1" ]
then
	# Clear out unused flatpak apps
	flatpak uninstall --unused

	# Update flatpak packages
	flatpak update

	# Clear out unused flatpak apps once again
	flatpak uninstall --unused
fi

if [ "${RUN[gem]}" = "1" ]
then
	gem update --system
	gem update
fi

if [ "${RUN[nvim]}" = "1" ]
then
	nvim --headless -c 'Lazy! sync' -c 'quitall'
fi

if [ "${RUN[vim]}" = "1" ]
then
	command vim +PlugUpdate +qall
fi

if [ "${RUN[mise]}" = "1" ]
then
	mise self-update
fi

if [ "${RUN[brew]}" = "1" ]
then
	brew update
	brew upgrade
	if [ "$UNAME" = "Darwin" ]; then
		brew upgrade --cask
	fi
	if [ $? -eq 0 ]; then
		echo $( date +%s ) > $MY_CONFIG_CACHE_DIR/brew-upgrade-date
	fi
fi

if [ "${RUN[pacman]}" = "1" ]
then
	# Clear out orphans once again
	sudo pacman -Rns $(pacman -Qtdq)
fi