#!/bin/bash

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

STATUSVAR=1
# EDITOR is often unset, so look for an editor that exists
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"
}
SELECTEDITEM=""

# =======================
# Service messages section
# Wrong Option
ERRORMSG="$RED Wrong option $NC"
TRYAGAINMSG=" Please try again..."
#
CONTINMSG="$RED To return press ENTER $NC"
CURRENTPREFIXMSG="(current: "
CURRENTSUFFIXMSG="):"
AVAILABLESHELLMSG="Available shells "
AVAILABLEDMMSG="Available display managers "
PS3SHELLCHOOSMSG="Which shell do you wish to install and use as default? "
ZSH1MSG="Z shell. Advanced and versatile shell with supreme configuration options and tab completion. Master of all trades, jack of none, but really needs configuration."
ZSH2MSG="check oh-my-zsh or builtin configuration tool for configurations"
ZSH3MSG="you might also like zsh-history-substring search or zsh-syntax-highlighting"
BASH1MSG="Bourne again shell. Standard for most linux systems. Respectable choice for any use. Jack of all trades, master of none."
FISH1MSG="Friendly interactive shell. Bad for scripting, great for interactive use without much configuration required."
DASH1MSG="Debian almquist shell. Super light and feature free. Great for scripting and fast startup, entirely unsuitable for interactive use."
PS3DISPLAYMNGMSG="Which displaymanager do you wish to install and use as default? "
PS3DISKUTILSMSG="Select tool to use? "
PS3CHOOSESESSIONMSG="Which session do you wish to use as default? "
NOSYSTEMDMSG="This menu configures systemd units and this system does not run systemd."
NODMMSG="No display manager was detected. Install one first (entry 1 of this menu)."
CURRENTSHELLMSG="$(echo "$SHELL")"
SETSUFFIXMSG=" was set successfully"
SHELLPREFIXMSG="Shell "
DISPLAYMGRPREFIXMSG="Display manager "
AUTOLOGGERRPREFIXMSG="Autologger"
PRINTERSUPPORTMSG="Printer support"

# Paths the display manager edits work on
GDM_CONF=${BMENU_GDM_CONF:-/etc/gdm/custom.conf}
LIGHTDM_CONF=${BMENU_LIGHTDM_CONF:-/etc/lightdm/lightdm.conf}
# Session lists and the sddm config
XSESSIONS_DIR=${BMENU_XSESSIONS_DIR:-/usr/share/xsessions}
WAYLAND_SESSIONS_DIR=${BMENU_WAYLAND_SESSIONS_DIR:-/usr/share/wayland-sessions}
SDDM_CONF=${BMENU_SDDM_CONF:-/etc/sddm.conf}
# Autologin configs of the other display managers
LXDM_CONF=${BMENU_LXDM_CONF:-/etc/lxdm/lxdm.conf}
SLIM_CONF=${BMENU_SLIM_CONF:-/etc/slim.conf}

# =======================
# Init system detection: every entry writes systemd units and display manager configs
# 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)}

function require_systemd() {
	if [ "$INIT_COMM" != "systemd" ]; then
		echo -e "$NOSYSTEMDMSG"
		return 1
	fi
	return 0
}

# =======================
# Distro detection: manjaro-printer only exists on Manjaro
IS_MANJARO=0
if grep -q '^ID=manjaro' /etc/os-release 2>/dev/null; then
	IS_MANJARO=1
fi

# =======================
# Pacman installation
INSTALLPKGS="sudo pacman -Syu"

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

# chsh is setuid and can fail without a terminal; a failure names the command to run by hand
function set_login_shell() { # <path>
	if ! chsh -s "$1"; then
		echo "The login shell was NOT changed to $1."
		echo "Run it yourself with: sudo chsh -s $1"
		return 1
	fi
	return 0
}

function shell_chooser() {
	echo "$AVAILABLESHELLMSG$CURRENTPREFIXMSG$CURRENTSHELLMSG$CURRENTSUFFIXMSG"
	PS3="$PS3SHELLCHOOSMSG"
	SELECTEDITEM=""
	# Gather the results in an array.
	shells=("zsh" "bash" "fish" "dash" "cancel")

	select pick in "${shells[@]}"; do
		case $pick in
		zsh)
			echo ""
			echo "$ZSH1MSG"
			echo ""
			echo ""
			$INSTALLPKGS zsh zsh-completions
			STATUSVAR=$?
			if [ $STATUSVAR -eq 1 ]; then
				return $STATUSVAR
			fi
			echo ""
			echo ""
			echo "$ZSH2MSG"
			echo "$ZSH3MSG"
			echo ""
			echo ""
			set_login_shell /usr/bin/zsh || STATUSVAR=1
			SELECTEDITEM="$pick"
			break
			;;
		bash)
			echo ""
			echo ""
			echo "$BASH1MSG"
			echo ""
			echo ""
			$INSTALLPKGS bash bash-completion
			STATUSVAR=$?
			if [ $STATUSVAR -eq 1 ]; then
				return $STATUSVAR
			fi
			echo ""
			set_login_shell /bin/bash || STATUSVAR=1
			SELECTEDITEM="$pick"
			break
			;;
		fish)
			echo ""
			echo ""
			echo "$FISH1MSG"
			echo ""
			echo ""
			$INSTALLPKGS fish
			STATUSVAR=$?
			if [ $STATUSVAR -eq 1 ]; then
				return $STATUSVAR
			fi
			set_login_shell /usr/bin/fish || STATUSVAR=1
			SELECTEDITEM="$pick"
			break
			;;
		dash)
			echo ""
			echo ""
			echo "$DASH1MSG"
			$INSTALLPKGS dash
			STATUSVAR=$?
			if [ $STATUSVAR -eq 1 ]; then
				return $STATUSVAR
			fi
			set_login_shell /usr/bin/dash || STATUSVAR=1
			SELECTEDITEM="$pick"
			break
			;;
		cancel)
			# A cancel is not a success
			STATUSVAR=1
			break
			;;
		esac
	done
	return $STATUSVAR
}

function displaymanager() {
	require_systemd || return 1
	CURRENTITEM=$(dm_detect)
	if [ "$CURRENTITEM" == "" ]; then
		CURRENTITEM="none"
	fi
	PS3="$PS3DISPLAYMNGMSG"
	SELECTEDITEM=""
	# Gather the results in an array.
	dms=("lightdm" "gdm" "lxdm" "slim" "sddm" "cancel")
	sudo echo ""
	STATUSVAR=$?
	if [ $STATUSVAR -eq 1 ]; then
		return $STATUSVAR
	fi
	echo "$AVAILABLEDMMSG$CURRENTPREFIXMSG$CURRENTITEM$CURRENTSUFFIXMSG"
	select pick in "${dms[@]}"; do
		case $pick in
		slim)
			SELECTEDITEM="$pick"
			$INSTALLPKGS slim && sudo systemctl enable slim.service -f
			STATUSVAR=$?
			break
			;;
		lightdm)
			SELECTEDITEM="$pick"
			$INSTALLPKGS lightdm lightdm-gtk-greeter lightdm-gtk-greeter-settings accountsservice &&
				sudo systemctl enable lightdm.service -f && sudo systemctl enable accounts-daemon &&
				run_editor "$LIGHTDM_CONF"
			STATUSVAR=$?
			break
			;;
		sddm)
			SELECTEDITEM="$pick"
			$INSTALLPKGS sddm && sudo systemctl enable sddm.service -f
			STATUSVAR=$?
			if [ $STATUSVAR -eq 1 ]; then
				return $STATUSVAR
			fi
			break
			;;
		lxdm)
			SELECTEDITEM="$pick"
			$INSTALLPKGS lxdm && sudo systemctl enable lxdm.service -f
			STATUSVAR=$?
			break
			;;
		gdm)
			SELECTEDITEM="$pick"
			$INSTALLPKGS gdm && sudo systemctl enable gdm.service -f
			STATUSVAR=$?
			break
			;;
		cancel)
			STATUSVAR=1
			break
			;;
		esac
	done
	return $STATUSVAR
}

# A tool can live in a package with another name
function require_tool() { # <binary> <package>
	if command -v "$1" >/dev/null 2>&1; then
		return 0
	fi
	echo "$1 is not installed. Installing $2."
	if [ -e /var/lib/pacman/db.lck ]; then
		echo "$2 is not installed and pacman seems to be in use"
		return 1
	fi
	$INSTALLPKGS "$2"
}

# The partition editors need a device, so ask for one: whole disks only
function pick_disk() {
	echo "Available disks:"
	# The type is the last column: a partition line has no model
	lsblk -rno NAME,SIZE,MODEL,TYPE 2>/dev/null |
		awk '$NF == "disk" { printf "  /dev/%s", $1; for (i = 2; i < NF; i++) printf " %s", $i; print "" }' |
		sed -e 's/\\x20/ /g'
	# The answer goes to a root partition editor, so an empty line is asked again
	local dev empty=0
	while true; do
		if ! read -r -p "Device path (e.g. /dev/sda): " dev; then
			[ -n "$dev" ] || { echo "No device given, nothing was opened."; return 1; }
			break
		fi
		[ -n "$dev" ] && break
		echo "No device given yet."
		if ! [ -t 0 ]; then
			empty=$((empty + 1))
			[ "$empty" -lt 3 ] || return 1
		fi
	done
	case "$dev" in
	/*) ;;
	*) dev="/dev/$dev" ;;
	esac
	dev=$(realpath -m "$dev")
	if ! [ -b "$dev" ]; then
		echo "No block device: $dev"
		return 1
	fi
	# The kernel tree says whether this is a whole disk: a partition has no /sys/block entry
	if ! [ -d "/sys/block/$(basename "$dev")" ]; then
		echo "$dev is not a whole disk. Pick one of the disks listed above."
		return 1
	fi
	DISK="$dev"
	return 0
}

function disk_utils() {
	PS3="$PS3DISKUTILSMSG"
	# Gather the results in an array.
	tools=("cfdisk" "cgdisk" "gdisk" "parted" "gparted" "gnome-disks" "cancel")

	select pick in "${tools[@]}"; do
		case $pick in
		cfdisk)
			require_tool cfdisk util-linux && pick_disk && sudo cfdisk "$DISK"
			break
			;;
		cgdisk)
			require_tool cgdisk gptfdisk && pick_disk && sudo cgdisk "$DISK"
			break
			;;
		gdisk)
			require_tool gdisk gptfdisk && pick_disk && sudo gdisk "$DISK"
			break
			;;
		parted)
			require_tool parted parted && pick_disk && sudo parted "$DISK"
			break
			;;
		gparted)
			require_tool gparted gparted && sudo gparted
			break
			;;
		gnome-disks)
			require_tool gnome-disks gnome-disk-utility && sudo gnome-disks
			break
			;;
		cancel)
			break
			;;
		esac
	done
}

function dm_detect() {
	# display-manager.service is the alias of the active greeter; its
	# ExecStart line names the display manager's binary
	exec_line=$(systemctl cat display-manager.service 2>/dev/null | grep '^ExecStart')
	for displaymanager in gdm sddm lightdm lxdm slim; do
		echo "$exec_line" | grep -q "/$displaymanager" && { echo "$displaymanager"; return 0; }
	done
	echo ""
}

# Both session kinds are offered: X11 and Wayland
function choose_session() {
	PS3="$PS3CHOOSESESSIONMSG"
	sessions=()
	while read -r f; do
		[ -n "$f" ] && sessions+=("x11 $f")
	done < <(ls "$XSESSIONS_DIR" 2>/dev/null)
	while read -r f; do
		[ -n "$f" ] && sessions+=("wayland $f")
	done < <(ls "$WAYLAND_SESSIONS_DIR" 2>/dev/null)
	if [ ${#sessions[@]} -eq 0 ]; then
		echo "No session files in $XSESSIONS_DIR or $WAYLAND_SESSIONS_DIR."
		STATUSVAR=1
		return 1
	fi
	sessions+=("cancel")
	select pick in "${sessions[@]}"; do
		case $pick in
		cancel)
			STATUSVAR=1
			break
			;;
		"")
			# An empty line re-shows the list
			continue
			;;
		*)
			STATUSVAR=0
			echo "$pick"
			break
			;;
		esac
	done
}

# =======================
# Display manager config writes
# The packaged configs keep the autologin keys commented inside their own section

# Replace an active key, uncomment a commented one, or add the key inside its section
function set_ini_key() { # <file> <section> <key> <value>
	local file="$1" section="$2" key="$3" value="$4" line
	if sudo grep -qE "^[[:space:]]*${key}=" "$file"; then
		sudo sed -i -E "s/^([[:space:]]*)${key}=.*/\1${key}=${value}/" "$file"
		return 0
	fi
	if sudo grep -qE "^[[:space:]]*#[[:space:]]*${key}=" "$file"; then
		sudo sed -i -E "s/^([[:space:]]*)#[[:space:]]*${key}=.*/\1${key}=${value}/" "$file"
		return 0
	fi
	line=$(sudo grep -n -F "[${section}]" "$file" | head -1 | cut -d: -f1)
	if [ -n "$line" ]; then
		sudo sed -i "${line}a ${key}=${value}" "$file"
		return 0
	fi
	printf '[%s]\n%s=%s\n' "$section" "$key" "$value" | sudo tee -a "$file" >/dev/null
}

# Read back the value: sed and tee exit 0 even when nothing matched
function ini_key_active() { # <file> <section> <key> <value>
	sudo cat "$1" | awk -v sec="$2" -v key="$3" -v want="$4" '
		/^[[:space:]]*\[/ { insec = (index($0, "[" sec "]") > 0); next }
		!insec { next }
		{
			line = $0
			sub(/^[[:space:]]*/, "", line)
			if (index(line, key "=") == 1 && substr(line, length(key) + 2) == want) found = 1
		}
		END { exit !found }'
}

# slim is not an INI file: key and value are separated by whitespace, no '='
function set_slim_key() { # <file> <key> <value>
	if sudo grep -qE "^[[:space:]]*#?[[:space:]]*$2[[:space:]]" "$1"; then
		sudo sed -i -E "s/^([[:space:]]*)#?[[:space:]]*$2[[:space:]]+.*/\1$2       $3/" "$1"
		return 0
	fi
	printf '%s       %s\n' "$2" "$3" | sudo tee -a "$1" >/dev/null
}

function slim_key_active() { # <file> <key> <value>
	sudo cat "$1" | grep -qE "^[[:space:]]*$2[[:space:]]+$3([[:space:]]|$)"
}

# A clear failure when the config does not carry the setting
function autologin_check() { # <file> <message name>
	if [ "$STATUSVAR" -eq 0 ]; then
		return 0
	fi
	echo -e "$RED Autologin was NOT enabled in $1. Edit that file by hand. $NC"
	return 1
}

function autologger() {
	require_systemd || return 1
	sudo echo ""
	STATUSVAR=$?
	if [ $STATUSVAR -eq 1 ]; then
		return $STATUSVAR
	fi
	dm=$(dm_detect)
	user=$(whoami)
	case "$dm" in
	slim)
		if ! sudo test -e "$SLIM_CONF"; then
			echo "No $SLIM_CONF here. Install slim first (entry 1 of this menu)."
			return 1
		fi
		# slim keys are default_user and auto_login
		set_slim_key "$SLIM_CONF" default_user "$user"
		set_slim_key "$SLIM_CONF" auto_login yes
		if slim_key_active "$SLIM_CONF" default_user "$user" && slim_key_active "$SLIM_CONF" auto_login yes; then
			STATUSVAR=0
		else
			STATUSVAR=1
		fi
		autologin_check "$SLIM_CONF" || return 1
		;;
	lightdm)
		# Only a missing config is created, a user's file is never replaced
		if [ ! -e "$LIGHTDM_CONF" ]; then
			sudo mkdir -p "$(dirname "$LIGHTDM_CONF")"
			for src in /etc/lightdm/lightdm.conf.d/*.conf; do
				[ -e "$src" ] || continue
				sudo cp "$src" "$LIGHTDM_CONF"
				break
			done
			# A new file needs its [Seat:*] section
			[ -e "$LIGHTDM_CONF" ] || printf '[Seat:*]\n' | sudo tee "$LIGHTDM_CONF" >/dev/null
		fi
		set_ini_key "$LIGHTDM_CONF" 'Seat:*' autologin-user "$user"
		set_ini_key "$LIGHTDM_CONF" 'Seat:*' autologin-user-timeout 0
		sudo groupadd -r autologin 2>/dev/null
		sudo gpasswd -a "$user" autologin
		if ini_key_active "$LIGHTDM_CONF" 'Seat:*' autologin-user "$user" &&
			ini_key_active "$LIGHTDM_CONF" 'Seat:*' autologin-user-timeout 0; then
			STATUSVAR=0
		else
			STATUSVAR=1
		fi
		autologin_check "$LIGHTDM_CONF" || return 1
		run_editor "$LIGHTDM_CONF"
		;;
	sddm)
		session_line=$(choose_session)
		if [ $STATUSVAR -eq 1 ] || [ -z "$session_line" ]; then
			return 1
		fi
		session=${session_line#* }
		# A user-edited config is kept, only a missing one is generated
		if [ ! -e "$SDDM_CONF" ]; then
			sddm --example-config | sudo tee "$SDDM_CONF" >/dev/null || return 1
			[ -s "$SDDM_CONF" ] || {
				echo "sddm produced no configuration, nothing was written to $SDDM_CONF."
				return 1
			}
		fi
		set_ini_key "$SDDM_CONF" Autologin User "$user"
		set_ini_key "$SDDM_CONF" Autologin Session "$session"
		if ini_key_active "$SDDM_CONF" Autologin User "$user" &&
			ini_key_active "$SDDM_CONF" Autologin Session "$session"; then
			STATUSVAR=0
		else
			STATUSVAR=1
		fi
		autologin_check "$SDDM_CONF" || return 1
		;;
	lxdm)
		if ! sudo test -e "$LXDM_CONF"; then
			echo "No $LXDM_CONF here. Install lxdm first (entry 1 of this menu)."
			return 1
		fi
		set_ini_key "$LXDM_CONF" base autologin "$user"
		if ini_key_active "$LXDM_CONF" base autologin "$user"; then
			STATUSVAR=0
		else
			STATUSVAR=1
		fi
		autologin_check "$LXDM_CONF" || return 1
		run_editor "$LXDM_CONF"
		;;
	gdm)
		# gdm reads these two keys from [daemon]
		[ -e "$GDM_CONF" ] || sudo touch "$GDM_CONF"
		set_ini_key "$GDM_CONF" daemon AutomaticLogin "$user"
		set_ini_key "$GDM_CONF" daemon AutomaticLoginEnable true
		if ini_key_active "$GDM_CONF" daemon AutomaticLogin "$user" &&
			ini_key_active "$GDM_CONF" daemon AutomaticLoginEnable true; then
			STATUSVAR=0
		else
			STATUSVAR=1
		fi
		autologin_check "$GDM_CONF" || return 1
		;;
	*)
		echo -e "$NODMMSG"
		return 1
		;;
	esac
	return $STATUSVAR
}

function _recover() {
	if [ -e /usr/bin/photorec ]; then
		photorec
	else
		echo "Installing the testdisk recovery tool"
		if [ -e /var/lib/pacman/db.lck ]; then
			echo "Testdisk is not installed and pacman seems to be in use"
		else
			$INSTALLPKGS testdisk && testdisk
		fi
	fi
}

function main() {

	# Define Menu entries which will be run with the echo command
	E0="\e[1mQ\e[0muit"
	E1="Install Display \e[1mM\e[0manager"
	E2="\e[1mE\e[0mnable Autologin"
	E3="Install \e[1mS\e[0mhell"
	E4="\e[1mD\e[0misk Utility"
	E5="Install \e[1mP\e[0mrinter Support"
	E6="Recover \e[1mF\e[0miles"

	while true; do

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

		echo
		echo -e "                               $BG$TC Setup $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"
		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 | m | M)
			echo
			displaymanager
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				echo ""
				echo -e "$DISPLAYMGRPREFIXMSG$SELECTEDITEM$SETSUFFIXMSG"
				pressanykeyrequest
			fi
			echo ""
			;;
		2 | e | E)
			echo
			autologger
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				echo ""
				echo -e "$AUTOLOGGERRPREFIXMSG$SETSUFFIXMSG"
				pressanykeyrequest
			fi
			echo ""
			;;
		3 | s | S)
			echo
			shell_chooser
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				echo ""
				echo -e "$SHELLPREFIXMSG$SELECTEDITEM$SETSUFFIXMSG"
				pressanykeyrequest
			fi
			echo ""
			;;
		4 | d | D)
			echo
			disk_utils
			echo ""
			;;
		5 | p | P)
			echo
			if [ "$IS_MANJARO" == "1" ]; then
				$INSTALLPKGS manjaro-printer sane
			else
				$INSTALLPKGS cups sane
			fi
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				echo ""
				echo -e "$PRINTERSUPPORTMSG$SETSUFFIXMSG"
				pressanykeyrequest
			fi
			echo ""
			;;
		6 | f | F)
			echo
			_recover
			echo ""
			;;
		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

