#!/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..."
netcommand=""
NETMODE=""
NOSYSTEMDMSG="This menu configures systemd units and this system does not run systemd."
# BMENU_INIT_COMM names the init system the way /proc/1/comm does
INIT_COMM=${BMENU_INIT_COMM:-$(cat /proc/1/comm 2>/dev/null)}
if [ "$INIT_COMM" = "systemd" ]; then
	# is-active answers by exit code, so no status text is parsed
	systemctl is-active --quiet NetworkManager.service && netcommand="nmtui"
	# A netctl profile runs as netctl@<profile>.service, not netctl.service
	systemctl list-units --type=service --state=active --no-legend 2>/dev/null |
		grep -qE 'netctl(-auto)?@' && netcommand="sudo wifi-menu"
	if [ -z "$netcommand" ] && systemctl is-active --quiet systemd-networkd.service; then
		# systemd-networkd has no terminal UI
		NETMODE="networkd"
	fi
else
	# Without systemd there is no service state to read
	NETMODE="noinit"
fi

# 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
}

function init_settings() {
	if [ "$INIT_COMM" = "systemd" ]; then
		initmenu
	else
		echo "$NOSYSTEMDMSG"
		echo "initmenu manages systemd units; this system needs its own init commands."
	fi
}

# Startmenu for releasecompare
function releasecompare_startmenu() {
	# The answer is read as a whole line
	local empty=0
	while true; do
		printf '\33[H\33[2J'
		echo ""
		echo -e "$TC This tool will compare the release package list of Manjaro, $NC"
		echo -e "$TC or any Arch based distro to the local system. $NC"
		echo ""
		echo "  1) Compare only"
		echo "  2) Installation Options"
		echo "  0) Quit"
		# No input (EOF) ends the chooser
		if ! read -r choice; then
			# A last line without a trailing newline still carries the answer
			[ -n "$choice" ] || return 1
		fi
		case "$choice" in
		1)
			echo "you chose to compare only"
			releasecompare
			return 0
			;;
		2)
			echo "you chose Installation Options"
			releasecompare install
			return 0
			;;
		0 | q)
			return 1
			;;
		"")
			# An empty line carries no choice: ask again
			if [ -t 0 ]; then
				continue
			fi
			empty=$((empty + 1))
			[ "$empty" -lt 3 ] || return 1
			continue
			;;
		*) # do this, if $choice variable contains anything else not offered above
			echo -e "$ERRORMSG"
			sleep 1
			;;
		esac
	done
}

function main() {
	# Run infinite loop for UI / menu, till the user quits using the "quit" option or CTRL+C.
	while true; do

		# Define Menu entries which will be run with the echo command
		E0="\e[1mQ\e[0muit"
		E1="\e[1mA\e[0mppearance"
		E2="\e[1mN\e[0metwork"
		E3="System \e[1mC\e[0monfiguration"
		E4="\e[1mI\e[0mnit-System"
		E5="\e[1mR\e[0melease Comparison"

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

		echo
		echo -e "                         $BG$TC System & Settings $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$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 | A | a)
			echo
			appearance-menu
			echo ""
			;;
		2 | N | n)
			echo
			if [ -n "$netcommand" ]; then
				$netcommand
			elif [ "$NETMODE" == "networkd" ]; then
				echo "This system uses systemd-networkd, which has no terminal UI."
				echo "Edit the files in /etc/systemd/network/ and run: sudo systemctl restart systemd-networkd"
				echo "For a terminal Wi-Fi UI use NetworkManager (nmtui) or netctl (wifi-menu)."
			elif [ "$NETMODE" == "noinit" ]; then
				echo "$NOSYSTEMDMSG"
				echo "Start the tool for your network setup manually."
			else
				echo "No NetworkManager, netctl or systemd-networkd service is active."
				echo "Start the tool for your network setup manually."
			fi
			echo ""
			;;
		3 | C | c)
			echo
			system-settings
			echo ""
			;;
		4 | I | i)
			echo
			init_settings
			echo ""
			;;
		5 | R | r)
			printf '\33[H\33[2J'
			if releasecompare_startmenu; then
				cd || exit
				echo
				echo -e " $RED Displaying Releasecompare. To return to System & Settings press ENTER $NC"
				# wait for input, e.g. by pressing ENTER:
				read -r
			fi
			;;
		0 | Q | q)
			printf '\33[H\33[2J' && exit
			;;
		*) # do this, if $choice variable contains anything else not offered above
			echo -e "$ERRORMSG"
			echo -e "$TRYAGAINMSG"
			sleep 2
			;;
		esac
	done
}

main

