#!/bin/bash

pacfile="$HOME/.config/scripts/pacmanpkg.txt"
flatfile="$HOME/.config/scripts/flatpkg.txt"
carfile="$HOME/.config/scripts/carpkg.txt"

save() {
	pacvar=$(pacman -Q)
	flatvar=$(flatpak list | awk '{ print $2 }')
	if [ "$pacfile" != ' ' ]; then
		touch "$pacfile"
	fi
	if [ "$flatfile" != ' ' ]; then
		touch "$flatfile"
	fi
	if [ "$carfile" != ' ' ]; then
		touch "$carfile"
	fi
	echo "$pacvar" | awk '{ print $1 }' >"$pacfile"
	echo "$flatvar" >"$flatfile"
	mkdir -p $HOME/.local/bin/cargo/
	ls $HOME/.local/bin/cargo/bin/ >"$carfile"
}

load() {
	sudo paru -S - <"$pacfile"
}

install() {
	PKG=$(pacman -Ss "^$1$")
	if [ "$PKG" == '' ]; then
		CHOICE="F"
		read -p "Flatpak, cargo or aur? [F/c/a] " CHOICE
		if [ "$CHOICE" == 'F' ] || [ "$CHOICE" == '' ]; then
			flatpak install "$1"
		elif [ "$CHOICE" == 'c' ]; then
			mkdir -p $HOME/.local/bin/cargo/
			cargo install "$1" --root $HOME/.local/bin/cargo/
		else
			echo "warning, this is an aur package!"
			paru -S "$1"
		fi
	else
		paru -S "$1"
	fi
	save
}

remove() {
	PKG=$(pacman -Qs "$1")
	if [ "$PKG" == '' ]; then
		flatpak uninstall "$1"
	else
		sudo pacman -R "$1"
	fi
	save
}

update() {
	CHOICE="Y"
	read -p "Update pacman? [Y/n] " CHOICE
	if [ "$CHOICE" == 'Y' ] || [ "$CHOICE" == 'y' ]; then
		sudo pacman -Suy
	fi
	CHOICE="Y"
	read -p "Update flatpak? [Y/n] " CHOICE
	if [ "$CHOICE" == 'Y' ] || [ "$CHOICE" == 'y' ]; then
		flatpak update
	fi
	CHOICE="Y"
	read -p "Update AUR? [Y/n] " CHOICE
	if [ "$CHOICE" == 'Y' ] || [ "$CHOICE" == 'y' ]; then
		sudo paru -Suy
	fi
	CHOICE="Y"
}

if [ "$1" == "-S" ]; then
	install "$2"
elif [ "$1" == "-R" ]; then
	remove "$2"
elif [ "$1" == "-Suy" ]; then
	update
elif [ "$1" == "save" ]; then
	save
elif [ "$1" == "load" ]; then
	load
fi
