#!/bin/bash

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

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

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

# =======================
# Service messages section
# Wrong Option
ERRORMSG="$RED Wrong option $NC"
TRYAGAINMSG=" Please try again..."

# =======================
# Init system detection: every entry acts on systemd units
INIT_COMM=${BMENU_INIT_COMM:-$(cat /proc/1/comm 2>/dev/null)}
if [ "$INIT_COMM" != "systemd" ]; then
	echo "This menu manages systemd units and this system does not run systemd."
	echo "initmenu needs systemd; use your init system's own commands."
	exit 1
fi

#
CONTINMSG=" $RED To return to Init Menu press ENTER $NC"
SELECTFILEMSG="Select file to configure and press Enter: "
SELECTTARGETMSG="Select target and press Enter to change to: "
SERVICEPREFIXMSG="Service "
SERVICESTARTEDMSG=" was started successfully"
SERVICEENABLEDMSG=" was enabled successfully"
SERVICESTOPPEDMSG=" was stopped successfully"
SERVICEDISABLEDMSG=" was disabled successfully"

# 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 pressanykeyrequest() {
	echo -e "$CONTINMSG"
	read -r
	STATUSVAR=1
}

# Create a missing drop-in from the main config, then edit it
function edit_dropin() { # <dir> <drop-in file> <main config>
	local dir="$1" file="$2" main="$3"
	if [ ! -e "$file" ]; then
		sudo mkdir -p "$dir" || return 1
		sudo cp "$main" "$file" || return 1
	fi
	run_editor "$file"
}

function config_editor() {
	PS3="$SELECTFILEMSG"
	configs=("journald.conf" "system.conf" "logind.conf" "user.conf" "cancel")

	select pick in "${configs[@]}"; do
		case $pick in
		logind.conf)
			edit_dropin /etc/systemd/logind.conf.d /etc/systemd/logind.conf.d/10-logind.conf /etc/systemd/logind.conf
			break
			;;
		system.conf)
			edit_dropin /etc/systemd/system.conf.d /etc/systemd/system.conf.d/10-system.conf /etc/systemd/system.conf
			break
			;;
		journald.conf)
			edit_dropin /etc/systemd/journald.conf.d /etc/systemd/journald.conf.d/10-journald.conf /etc/systemd/journald.conf
			break
			;;
		user.conf)
			edit_dropin /etc/systemd/user.conf.d /etc/systemd/user.conf.d/10-user.conf /etc/systemd/user.conf
			break
			;;
		cancel)
			break
			;;
		esac
	done

}

function change_runlevel() {
	PS3="$SELECTTARGETMSG"
	targets=("poweroff" "rescue" "multi-user" "graphical" "reboot" "cancel")

	select pick in "${targets[@]}"; do
		case $pick in
		poweroff)
			sudo systemctl isolate poweroff.target
			break
			;;
		reboot)
			sudo systemctl isolate reboot.target
			break
			;;
		rescue)
			sudo systemctl isolate rescue.target
			break
			;;
		multi-user)
			sudo systemctl isolate multi-user.target
			break
			;;
		graphical)
			sudo systemctl isolate graphical.target
			break
			;;
		cancel)
			break
			;;
		esac
	done

}

# Template units and `not-found` rows cannot be acted on, so they are dropped
function filter_units() {
	awk '$0 !~ /@\./ && $0 !~ /[[:space:]]not-found[[:space:]]/'
}

# Only the unit name of a systemctl list line goes to systemctl
# $1 = systemctl action, $2 = the list command that offers matching units
function run_on_units() {
	action="$1"
	listcmd="$2"
	OUTPUTITEM=$($listcmd | filter_units | fzf -m -e --reverse)
	if [ -z "$OUTPUTITEM" ]; then
		return 1
	fi
	units=()
	while read -r line; do
		unit=$(printf '%s\n' "$line" | awk '{ for (i = 1; i <= NF; i++) if ($i ~ /\.(service|socket|target|mount|timer|device|path|slice|automount|swap)$/) { print $i; exit } }')
		[ -n "$unit" ] && units+=("$unit")
	done <<< "$OUTPUTITEM"
	[ "${#units[@]}" -gt 0 ] || return 1
	UNITLIST="${units[*]}"
	sudo systemctl "$action" "${units[@]}"
	STATUSVAR=$?
	return $STATUSVAR
}

function enable_services() {
	run_on_units enable 'systemctl list-unit-files --type=service --state=disabled --no-legend'
	return $?
}

function disable_services() {
	run_on_units disable 'systemctl list-unit-files --type=service --state=enabled --no-legend'
	return $?
}

# Start offers units that exist but are not running, stop offers running ones
function start_services() {
	run_on_units start 'systemctl list-units --type=service --all --state=inactive --no-legend'
	return $?
}

function stop_services() {
	run_on_units stop 'systemctl list-units --type=service --state=active --no-legend'
	return $?
}

function main() {

	# Define Menu entries which will be run with the echo command
	E0="\e[1mQ\e[0muit"
	E1="Enable Services"
	E2="Disable Services"
	E3="Start Services"
	E4="Stop Services"
	E5="List Active Services"
	E6="Show Boot Messages"
	E7="Edit Config Files"
	E8="Change Runlevel"
	E9="Analyze Boot"

	while true; do

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

		echo
		echo -e "                            $BG$TC Init-System $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             -    $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
			enable_services
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				echo -e "$SERVICEPREFIXMSG$UNITLIST$SERVICEENABLEDMSG"
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		2)
			echo
			disable_services
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				echo -e "$SERVICEPREFIXMSG$UNITLIST$SERVICEDISABLEDMSG"
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		3)
			echo
			start_services
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				echo -e "$SERVICEPREFIXMSG$UNITLIST$SERVICESTARTEDMSG"
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		4)
			echo
			stop_services
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				echo -e "$SERVICEPREFIXMSG$UNITLIST$SERVICESTOPPEDMSG"
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		5)
			echo
			systemctl
			echo ""
			pressanykeyrequest
			;;
		6)
			echo
			sudo dmesg
			echo ""
			pressanykeyrequest
			;;
		7)
			echo
			config_editor
			echo ""
			;;
		8)
			echo
			change_runlevel
			echo ""
			;;
		9)
			echo
			clear
			systemd-analyze blame
			echo ""
			pressanykeyrequest
			;;
		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
