#!/bin/bash

# =======================
# Define Colors
RED='\e[41m'
NC='\e[0m' # No color
BG='\e[7m' # Highlighting Background color
TC='\e[1m' # Highlighting Text color

# =======================
# Service messages section
# Wrong Option
ERRORMSG="$RED Wrong option $NC"
TRYAGAINMSG=" Please try again..."
#
# Drop an ENTER left in the input buffer by a menu key
function drain_enter() {
	local _rest
	read -r -n 1 -t 0.2 _rest || true
}

PS3SYSSETTMSG="Select bootloader to configure: "
CONTINMSG="$RED To return press ENTER $NC"
# EDITOR is used only when it points at a real command
function resolve_editor() {
	if [ -n "$EDITOR" ] && command -v "$EDITOR" >/dev/null 2>&1; then
		echo "$EDITOR"
		return 0
	fi
	for ed in nano vi vim; do
		command -v "$ed" >/dev/null 2>&1 && { command -v "$ed"; return 0; }
	done
	return 1
}
TEXTEDITOR=$(resolve_editor)
USINGEDITORMSG="No editor found. Install one with: sudo pacman -Syu nano"
# The boot loader files the entries edit
REFIND_LINUX_CONF=${BMENU_REFIND_LINUX_CONF:-/boot/refind_linux.conf}
REFIND_MAIN_CONF=${BMENU_REFIND_MAIN_CONF:-/boot/EFI/refind/refind.conf}
SYSLINUX_CONF=${BMENU_SYSLINUX_CONF:-/boot/syslinux/syslinux.cfg}

# Open a root-owned file
function run_editor() { # <file>
	if [ -z "$TEXTEDITOR" ]; then
		echo -e "$RED$USINGEDITORMSG${NC}"
		return 1
	fi
	sudo "$TEXTEDITOR" "$1"
}

# Arch has no update-grub, so grub-mkconfig refreshes grub.cfg there
function refresh_grub_config() {
	if command -v update-grub >/dev/null 2>&1; then
		sudo update-grub
	elif command -v archhw >/dev/null 2>&1; then
		sudo archhw refresh-grub --yes
	elif command -v grub-mkconfig >/dev/null 2>&1; then
		echo "No update-grub and no archhw here, generating grub.cfg directly."
		sudo grub-mkconfig -o /boot/grub/grub.cfg
	else
		echo "No GRUB refresh tool found. Run it yourself after editing /etc/default/grub:"
		echo "  sudo grub-mkconfig -o /boot/grub/grub.cfg"
	fi
}

function pressanykeyrequest() {
	echo -e "$CONTINMSG"
	read -r
	STATUSVAR=1
}

# A boot loader file is opened only when it exists
function edit_if_exists() { # <file> <one short sentence about what is missing>
	if [ -e "$1" ]; then
		run_editor "$1"
		return 0
	fi
	echo "No $1 here."
	echo " $2"
	return 1
}

function bootloader_configuration() {
	PS3="$PS3SYSSETTMSG"
	# Gather the results in an array.
	dms=("grub" "refind" "systemdboot" "syslinux" "cancel")

	select pick in "${dms[@]}"; do
		case $pick in
		grub)
			run_editor /etc/default/grub
			refresh_grub_config
			break
			;;
		refind)
			edit_if_exists "$REFIND_LINUX_CONF" "This system does not boot with rEFInd."
			edit_if_exists "$REFIND_MAIN_CONF" "Install rEFInd first if you want it."
			break
			;;
		systemdboot)
			entries=$(find /boot/loader/entries -maxdepth 1 -name '*.conf' 2>/dev/null | sort)
			if [ -z "$entries" ]; then
				echo "No systemd-boot entries found in /boot/loader/entries."
				echo "This system is likely not booted with systemd-boot."
			else
				PS3="Select the systemd-boot entry to edit: "
				# One item per line
				entry_list=()
				while IFS= read -r e; do
					[ -n "$e" ] && entry_list+=("$e")
				done <<< "$entries"
				entry_list+=("cancel")
				select entry in "${entry_list[@]}"; do
					case $entry in
					cancel)
						break
						;;
					"")
						echo "No such entry."
						;;
					*)
						run_editor "$entry"
						break
						;;
					esac
				done
			fi
			break
			;;
		syslinux)
			edit_if_exists "$SYSLINUX_CONF" "This system does not boot with syslinux."
			break
			;;
		cancel)
			break
			;;
		esac
	done
}

# visudo falls back to /usr/bin/vi, so it gets the editor this system has
function tryvisudo() {
	if [ -z "$TEXTEDITOR" ]; then
		echo -e "$RED$USINGEDITORMSG${NC}"
		return 1
	fi
	sudo EDITOR="$TEXTEDITOR" visudo
	return $?
}

function main() {

	# Define Menu entries which will be run with the echo command
	E0="\e[1mQ\e[0muit"
	E1="Pacman Settings"
	E2="Mkinitcpio"
	E3="Fstab"
	E4="Sudoers"
	E5="Logind"
	E6="Bootloader"
	E7="Udevil Settings"
	E8="Xinitrc"
	E9="Setup"

	while true; do
		printf '\33[H\33[2J' # Use this instead of the clear command

		echo
		echo -e "                           $BG$TC Configuration $NC"
		echo -e " $TC+----------------------------------------------------------------+$NC"
		echo -e " $TC|$NC    $BG 1 $NC $E1         $TC|$NC    $BG 2 $NC $E2             $TC|$NC"
		echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
		echo -e " $TC|$NC    $BG 3 $NC $E3                   $TC|$NC    $BG 4 $NC $E4                $TC|$NC"
		echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
		echo -e " $TC|$NC    $BG 5 $NC $E5                  $TC|$NC    $BG 6 $NC $E6             $TC|$NC"
		echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
		echo -e " $TC|$NC    $BG 7 $NC $E7 $NC        $TC|$NC    $BG 8 $NC $E8                $TC|$NC"
		echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
		echo -e " $TC|$NC    $BG 9 $NC $E9           $TC|$NC    $BG$TC T $NC$BG$TC O $NC$BG$TC O $NC$BG$TC L $NC $BG B $NC $BG O $NC $BG X $NC           $TC|$NC"
		echo -e " $TC+----------------------------------------------------------------+$NC"
		echo ""
		echo -e "  Enter marked number or letter   -    $BG 0 $NC $E0 "

		# save entered number/letter in variable "choice"
		read -r -n 1 -e choice || exit 0
		[ -n "$choice" ] && drain_enter
		if [ -z "$choice" ]; then
			# An empty answer is ENTER: redraw the menu
			if [ -t 0 ]; then
				continue
			fi
			EMPTY_RUNS=$((${EMPTY_RUNS:-0} + 1))
			[ "$EMPTY_RUNS" -lt 3 ] || exit 0
			continue
		fi
		EMPTY_RUNS=0

		# test, whether "choice" fits any of the following numbers or letters
		case "$choice" in
		1)
			echo
			run_editor /etc/pacman.conf
			echo ""
			;;
		2)
			echo
			run_editor /etc/mkinitcpio.conf
			echo ""
			;;
		3)
			echo
			run_editor /etc/fstab
			echo ""
			;;
		4)
			echo
			sudo echo ""
			STATUSVAR=$?
			if [ $STATUSVAR -eq 1 ]; then
				echo ""
			else
				tryvisudo
				STATUSVAR=$?
				if [ $STATUSVAR -eq 0 ]; then
					pressanykeyrequest
				fi
			fi
			echo ""
			;;
		5)
			echo
			run_editor /etc/systemd/logind.conf
			echo ""
			;;
		6)
			echo
			bootloader_configuration
			echo ""
			;;
		7)
			echo
			if [ -e /etc/udevil/udevil.conf ]; then
				run_editor /etc/udevil/udevil.conf
			else
				echo "udevil is not configured here: /etc/udevil/udevil.conf does not exist."
				echo "udevil is not in the repositories of Arch or Manjaro (it comes from the AUR)."
			fi
			echo ""
			;;
		8)
			echo
			if [ -z "$TEXTEDITOR" ]; then
				echo -e "$RED$USINGEDITORMSG${NC}"
			else
				"$TEXTEDITOR" "$HOME/.xinitrc"
			fi
			echo ""
			;;
		9)
			echo
			system-setup
			echo ""
			;;
		0 | Q | q)
			printf '\33[H\33[2J' && exit
			;;
		*)
			echo -e "$ERRORMSG"
			echo -e "$TRYAGAINMSG"
			sleep 2
			;;
		esac
	done
}
main
