#!/usr/bin/env bash
# AUR package list
aur_list=(
# nomachine
# realvnc-vnc-viewer
# jdownloader2
# ledger-live-bin
# czkawka-gui-bin
)

# Optional packages list
optional=(
firefox firefox-decentraleyes firefox-ublock-origin
ark okular shotwell mpv ffmpegthumbs
veracrypt keepassxc
# nextcloud-client
# ntfs-3g exfatprogs
# libreoffice-fresh
# remmina libvncserver
# torbrowser-launcher
# thunderbird
# filezilla
# chromium
# vlc
# gnome-disk-utility
# xdg-user-dirs
# noto-fonts-cjk
# noto-fonts-emoji
)

function INSTALL
{
	sudo pacman --sync ${@} --ask 4
	echo
}

# VirtualBox
until [[ ${install_virtualbox} = [yYnN] ]]
do
	read -n 1 -p $'\n\e[1mWould you like to install Virtualbox? (y/n): \e[0m' install_virtualbox
	[[ ${install_virtualbox} = [yYnN] ]] || echo -e -n '\n\n\e[1;31mNot a valid answer, type "y" or "n"\e[0m'
done
echo
# QEMU
until [[ ${install_qemu} = [yYnN] ]]
do
	read -n 1 -p $'\n\e[1mWould you like to install QEMU? (y/n): \e[0m' install_qemu
	[[ ${install_qemu} = [yYnN] ]] || echo -e -n '\n\n\e[1;31mNot a valid answer, type "y" or "n"\e[0m'
done

echo
echo

# Package groups installation
INSTALL ${optional[@]}

# Remmina
if [[ ${optional[@]} =~ "remmina" ]] && [ -d ~/.config/sway/config.d/ ]
then
	# Remmina passthrough
	cat > ~/.config/sway/config.d/zz-remmina <<- 'remmina'
	# VNC passthrough
	mode remmina {
	    bindsym Mod4+Shift+p mode default
	}
	bindsym Mod4+Shift+p mode remmina
	remmina
fi

# Tor
if [[ ${optional[@]} =~ "torbrowser-launcher" ]]
then
	torbrowser-launcher
fi

# Bluetooth
if pacman -Q | grep -q bluez-utils
then
	INSTALL bluedevil
	sudo systemctl --quiet enable --now bluetooth.service
fi

# AUR packages
if [ ${#aur_list[@]} -gt 0 ]
then
	if ! pacman -Q | grep -q -w git
	then
		INSTALL git
	fi
	echo -e '#!/usr/bin/env bash' > ~/.local/functions/aur-packages
	for aur_package in ${aur_list[@]}
	do
		cd
		git clone https://aur.archlinux.org/${aur_package}.git
		if echo ${aur_package} | grep -q nomachine
		then
			sed -i 's/_autoservice=n/_autoservice=y/' nomachine/PKGBUILD
			sed -i 's/_autofirewall=n/_autofirewall=y/' nomachine/PKGBUILD
		fi
		cd ${aur_package}/
		makepkg -csi
		echo
		cd ..
		rm -r ${aur_package}/ -f
		cat >> ~/.local/functions/aur-packages <<- aur
		function aur-${aur_package}
		{
		    cd ~/
		    git clone https://aur.archlinux.org/${aur_package}.git
		    cd ${aur_package}/
		    makepkg -csi
		    echo
		    cd ~/
		    rm -r ${aur_package}/ -f
		}

		aur
	done
fi

# Optional AUR extras
# freefilesync
# pdfsam
# fslint pygtk

# Printers
#     yay -S --ask 4 print-manager cups system-config-printer skanlite && echo && sudo systemctl --quiet enable --now org.cups.cupsd && sudo gpasswd -a ${USER} sys >/dev/null
# Webcam
#     sudo gpasswd -a ${USER} video >/dev/null

# i3
if [ -f ~/.config/i3/config ]
then
	cat >> ~/.config/i3/config <<- 'config'

	# gaps inner 8
	# gaps outer 4
	# for_window [class="^.*"] border pixel 2
	config

	cat > ~/.local/functions/i3-config <<- 'config'
	#!/usr/bin/env bash
	# i3 config
	function i3-config
	{
	    vim ~/.config/i3/config
	}
	config

	if [ -f /usr/share/xsessions/plasma-i3.desktop ]
	then
		tee -a ~/.config/i3/config >/dev/null <<- 'integration'

		# >>> Plasma Integration <<<
		# Try to kill the wallpaper set by Plasma (it takes up the entire workspace and hides everything)
		exec --no-startup-id wmctrl -c Plasma
		for_window [title="Desktop — Plasma"] kill; floating enable; border none
		no_focus [class=”plasmashell”]

		# Avoid tiling popups, dropdown windows from plasma
		for_window [class="plasmashell"] floating enable
		for_window [class="Plasma"] floating enable
		for_window [class="krunner"] floating enable
		for_window [class="Kmix"] floating enable
		for_window [class="Klipper"] floating enable
		for_window [class="Plasmoidviewer"] floating enable

		# >>> Window Rules <<<
		# >>> Avoid tiling for non-Plasma stuff <<<
		for_window [window_role="pop-up"] floating enable
		for_window [window_role="bubble"] floating enable
		for_window [window_role="task_dialog"] floating enable
		for_window [window_role="Preferences"] floating enable
		for_window [window_role="About"] floating enable
		for_window [window_type="dialog"] floating enable
		for_window [window_type="menu"] floating enable
		integration

		install /dev/stdin ~/.local/bin/rotate-wallpapers <<- feh
		#!/usr/bin/env bash
		sleep 1
		while true
		do
		    feh --bg-max --randomize /home/${USER}/Pictures
		    sleep 15
		done
		feh
	else
		if ls -l /dev/disk/* | grep -q 'VBOX'
		then
			echo 'exec VBoxClient-all' >> ~/.config/i3/config
		elif ls -l /dev/disk/* | grep -q 'virtio\|QEMU'
		then
			echo 'exec spice-vdagent' >> ~/.config/i3/config
		fi
	fi
fi

# Sway nextcloud
if [[ ${optional[@]} =~ "nextcloud-client" ]] && [ -f ~/.config/sway/config.d/zz-sway ]
then
	cat > ~/.config/sway/config.d/zz-nextcloud <<- 'nextcloud'
	# Nextcloud
	exec nextcloud
	for_window [title="Nextcloud Settings"] floating enable
	nextcloud
fi

# Virtualbox
if [[ ${install_virtualbox} = [yY] ]]
then
	echo 'Installing Virtualbox'

	if uname -r | grep -q 'lts\|hardened\|zen'
	then
		host_modules='virtualbox-host-dkms'
	else
		host_modules='virtualbox-host-modules-arch'
	fi

	INSTALL virtualbox ${host_modules} virtualbox-guest-iso
	echo

	sudo gpasswd -a ${USER} vboxusers >/dev/null
	echo

	if findmnt '/' | grep -q -w 'btrfs'
	then
		mkdir ~/VirtualBox\ VMs/
		chattr +C ~/VirtualBox\ VMs/
	fi
fi

# QEMU
if [[ ${install_qemu} = [yY] ]]
then
	echo 'Installing QEMU'
	INSTALL qemu-desktop virt-manager edk2-ovmf \
		dnsmasq dmidecode vde2 # bridge-utils

	echo
	echo "allow virbr0" | sudo tee /etc/qemu/bridge.conf >/dev/null

	# Make host system a pacman cache server
	sudo tee /etc/systemd/system/local-cacheserver.service >/dev/null <<- 'CACHESERVER'
	[Unit]
	Description=Python HTTP server for Pacman Cache Server

	[Service]
	ExecStart=/usr/bin/python3 -m http.server --directory /var/cache/pacman/pkg/ 9090
	Restart=always

	[Install]
	WantedBy=multi-user.target
	CACHESERVER

    # Host iptables rules as a pacman cache server
	sudo iptables -I INPUT -s 192.168.0.0/16 -p tcp -m tcp --dport 9090 -j ACCEPT -m comment --comment "Pacman cache server"
	sudo sed -i '/## Simple Firewall/i\
# Pacman cache server\
-A INPUT -s 192.168.0.0/16 -p tcp -m tcp --dport 9090 -j ACCEPT -m comment --comment "Pacman cache server"\n' \
	/etc/iptables/userinput.rules
	sed "/OUTPUT ACCEPT/r /etc/iptables/userinput.rules" /etc/iptables/simple_firewall.rules | sudo tee /etc/iptables/iptables.rules >/dev/null

	# QEMU pacman cache service
	sudo tee /etc/systemd/system/local-update-virtpkg-cache.service >/dev/null <<- 'service'
	[Unit]
	Description=Refresh package cache twice daily

	[Service]
	Type=oneshot
	ExecStart=/usr/bin/bash -c "/usr/bin/pacman -Syw -d --ask 4 $(curl --fail -s -L https://git.myvelabs.com/lab/archlinux/raw/branch/master/pkg/qemu)"
	service

	# QEMU pacman cache timer
	sudo tee /etc/systemd/system/local-update-virtpkg-cache.timer >/dev/null <<- 'timer'
	[Unit]
	Description=Refresh pacman package cache

	[Timer]
	OnCalendar=*-*-* 00/12:00:00
	RandomizedDelaySec=12h
	Persistent=true

	[Install]
	WantedBy=timers.target
	timer

	# Enable services
	sudo systemctl --quiet enable --now libvirtd.service
	sudo systemctl --quiet enable local-cacheserver.service local-update-virtpkg-cache.timer
	sudo virsh -q net-start default
	sudo virsh -q net-autostart default
	sudo gpasswd -a ${USER} libvirt >/dev/null
	echo
fi

rm -f ${0}
echo -e '\e[1;32mSupplementary installer completed, reboot one last time\e[0m\n'
