#!/bin/bash
## xinput_tui

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

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

# Pad a string to a visible width, color codes not counted
function pad_vis() {
	local text="$1" width="$2" plain
	plain=$(printf '%s' "$text" | sed -e 's/\x1b\[[0-9;]*[A-Za-z]//g' -e 's/\\e\[[0-9;]*[A-Za-z]//g')
	printf '%s' "$text"
	if [ "${#plain}" -lt "$width" ]; then
		printf '%*s' "$((width - ${#plain}))" ''
	fi
}

# Open a URL with the desktop helper
function open_url() { # <url>
	if command -v xdg-open >/dev/null 2>&1; then
		xdg-open "$1"
		return 0
	fi
	echo "No xdg-open here (package xdg-utils). Open this page in a browser:"
	echo "  $1"
	return 1
}

# Only the numeric id of the first touchpad is used
touchpad_id=$(xinput --list 2>/dev/null | grep -i "Touchpad" | grep -o 'id=[0-9]\+' | head -1 | sed 's/id=//g')

# Without a touchpad there is nothing to configure
function require_touchpad() {
	if [ -z "$touchpad_id" ]; then
		echo "No touchpad found. This entry needs an X session with a touchpad."
		echo "Press any key to continue"
		read -s -n1
		return 1
	fi
	return 0
}

toggle_natural_scrolling() {
	require_touchpad || return 1
	natural_scrolling_code=$(xinput --list-props "$touchpad_id" | grep "Natural Scrolling" | awk '{print $5}' | grep -o '[0-9]\+')

	if [[ $(xinput --list-props "$touchpad_id" | grep "Natural Scrolling Enabled (" | awk '{print $6}' | head -n1) == 1 ]]; then
		xinput --set-prop "$touchpad_id" "$natural_scrolling_code" 0 && echo "Natural scrolling is now disabled" || echo "Something went wrong"
	else
		xinput --set-prop "$touchpad_id" "$natural_scrolling_code" 1 && echo "Natural scrolling is now enabled" || echo "Something went wrong"
	fi

}

toggle_tap_to_click() {
	require_touchpad || return 1
	tap_to_click_code=$(xinput --list-props "$touchpad_id" | awk '/Tapping Enabled \(/ {print $4}' | grep -o '[0-9]\+')

	if [[ $(xinput --list-props "$touchpad_id" | awk '/Tapping Enabled \(/ {print $5}') == 1 ]]; then
		xinput --set-prop "$touchpad_id" "$tap_to_click_code" 0 && echo "Tap to click is now disabled" || echo "Something went wrong"
	else
		xinput --set-prop "$touchpad_id" "$tap_to_click_code" 1 && echo "Tap to click is now enabled" || echo "Something went wrong"
	fi

}

toggle_left_handed() {
	require_touchpad || return 1
	left_handed_code=$(xinput --list-props "$touchpad_id" | grep "Left Handed Enabled" | awk '{print $5}' | grep -o '[0-9]\+')

	if [[ $(xinput --list-props "$touchpad_id" | grep "Left Handed Enabled" | awk '{print $6}' | head -n1) == 1 ]]; then
		xinput --set-prop "$touchpad_id" "$left_handed_code" 0 && echo "Left handed mode is now disabled" || echo "Something went wrong"
	else
		xinput --set-prop "$touchpad_id" "$left_handed_code" 1 && echo "Left handed mode is now enabled" || echo "Something went wrong"
	fi

}

set_pointer_speed() {
	require_touchpad || return 1

	accel_speed_code=$(xinput --list-props "$touchpad_id" | awk '/Accel Speed \(/ {print $4}' | grep -o '[0-9]\+')
	current_speed=$(xinput --list-props "$touchpad_id" | awk '/Accel Speed \(/ {print $5}')

	echo ""
	echo "Setting pointer speed."
	echo "Current speed is $current_speed"
	if ! ask_speed; then
		echo "No value given, nothing changed."
		return 1
	fi
	# The value must be inside the range the prompt asks for
	if ! printf '%s\n' "$speed" | awk -v v="$speed" 'BEGIN { exit !(v ~ /^-?[0-9]*\.?[0-9]+$/ && v + 0 >= -1 && v + 0 <= 1) }'; then
		echo "Not a number between -1 and 1, nothing changed."
		return 1
	fi
	if ! xinput --set-prop "$touchpad_id" "$accel_speed_code" "$speed"; then
		echo "xinput rejected the value, nothing changed."
		return 1
	fi
	echo "Speed is now set to $speed."
	# A root write needs an answer: no input at all is not a yes
	if ! read -r -p "Do you wish to make this setting permanent? [Y/n] " response; then
		[ -n "$response" ] || response="n"
	fi
	case $response in
	[nN] | [nN][oO])
		echo "Not saved. The speed stays active for this X session only."
		;;
	*)
		# Identifier is a name, not the numeric xinput id, and the directory can be missing
		if sudo mkdir -p /etc/X11/xorg.conf.d &&
			sudo tee /etc/X11/xorg.conf.d/31-pointerspeed.conf >/dev/null <<XCFG
Section "InputClass"
	Identifier "toolbox-touchpad"
	Driver "libinput"
	MatchIsTouchpad "on"
	Option "AccelSpeed" "$speed"
EndSection
XCFG
		then
			echo "created file /etc/X11/xorg.conf.d/31-pointerspeed.conf"
		else
			echo "Could not write /etc/X11/xorg.conf.d/31-pointerspeed.conf."
		fi
		;;
	esac
	echo ""
	echo "Press any key to continue"
	read -r -s -n 1 _
}

toggle_drag_lock() {
	require_touchpad || return 1
	drag_lock_code=$(xinput --list-props "$touchpad_id" | grep "Drag Lock Enabled (" | awk '{print $6}' | grep -o '[0-9]\+')

	if [[ $(xinput --list-props "$touchpad_id" | grep "Drag Lock Enabled (" | awk '{print $7}' | head -n1) == 1 ]]; then
		xinput --set-prop "$touchpad_id" "$drag_lock_code" 0 && echo "Drag lock is now disabled" || echo "Something went wrong"
	else
		xinput --set-prop "$touchpad_id" "$drag_lock_code" 1 && echo "Drag lock is now enabled" || echo "Something went wrong"
	fi

}

toggle_disable_while_typing() {
	require_touchpad || return 1
	disable_while_typing_code=$(xinput --list-props "$touchpad_id" | grep "Disable While Typing Enabled (" | awk '{print $6}' | grep -o '[0-9]\+')

	# A value of 1 means the touchpad is off while typing, so the entry inverts it
	if [[ $(xinput --list-props "$touchpad_id" | grep "Disable While Typing Enabled (" | awk '{print $7}' | head -n1) == 1 ]]; then
		xinput --set-prop "$touchpad_id" "$disable_while_typing_code" 0 && echo "Touchpad is now enabled while typing" || echo "Something went wrong"
	else
		xinput --set-prop "$touchpad_id" "$disable_while_typing_code" 1 && echo "Touchpad is now disabled while typing" || echo "Something went wrong"
	fi

}

toggle_horizontal_scrolling() {
	require_touchpad || return 1
	horizontal_scrolling_code=$(xinput --list-props "$touchpad_id" | grep "Horizontal Scroll Enabled" | awk '{print $5}' | grep -o '[0-9]\+')

	if [[ $(xinput --list-props "$touchpad_id" | grep "Horizontal Scroll Enabled" | awk '{print $6}' | head -n1) == 1 ]]; then
		xinput --set-prop "$touchpad_id" "$horizontal_scrolling_code" 0 && echo "Horizontal scrolling is now disabled" || echo "Something went wrong"
	else
		xinput --set-prop "$touchpad_id" "$horizontal_scrolling_code" 1 && echo "Horizontal scrolling is now enabled" || echo "Something went wrong"
	fi

}

# A failed launch has to say so
function run_lxinput() {
	lxinput 2>/dev/null || echo "lxinput could not start (it needs an X session)."
}

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

# The speed is asked as a whole line
function ask_speed() { # -> sets speed
	local empty=0
	while true; do
		echo "input number between -1 and 1 and press enter"
		if ! read -r speed; then
			# A last line without a trailing newline still carries the answer
			[ -n "$speed" ] && return 0
			speed=""
			return 1
		fi
		if [ -n "$speed" ]; then
			return 0
		fi
		echo "No value given yet."
		if ! [ -t 0 ]; then
			empty=$((empty + 1))
			[ "$empty" -lt 3 ] || return 1
		fi
		done
}

function gui() {
	if [ -x "$(command -v lxinput)" ]; then
		run_lxinput
	else
		read -p "Lxinput is not installed. Should it be installed? (y/N)" -n 1 -r
		echo
		if [[ $REPLY =~ ^[Yy]$ ]]; then
			if [ -e /var/lib/pacman/db.lck ]; then
				echo "Pacman seems to be currently in use."
			else
				$INSTALLPKGS lxinput && run_lxinput
			fi
		fi
	fi
}

function main() {

	# Define Menu entries which will be run with the echo command
	E0="\e[1mQ\e[0muit"
	E1="Set Pointer Speed"
	E2="Toggle Tap to Click"
	E3="Toggle Drag Lock"
	E4="Toggle Left Handed Mode"
	E5="Toggle Disable While Typing"
	E6="Toggle Natural Scrolling"
	E7="Toggle Horizontal Scrolling"
	E8="Show Xinput Manual"
	E9="Show Xinput Wiki Entry"
	E10="Run \e[1mL\e[0mxinput" # (L)

	while true; do

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

		echo
		echo -e "                         $BG$TC Touchpad 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"
		echo -e " $TC|$NC    $BG 5 $NC $(pad_vis "$E5" 56)$TC|$NC"
		echo -e " $TC|$NC$(printf '%64s' '')$TC|$NC"
		echo -e " $TC|$NC    $BG 6 $NC $(pad_vis "$E6" 56)$TC|$NC"
		echo -e " $TC|$NC$(printf '%64s' '')$TC|$NC"
		echo -e " $TC|$NC    $BG 7 $NC $(pad_vis "$E7" 56)$TC|$NC"
		echo -e " $TC|$NC----------------------------------------------------------------$TC|$NC"
		echo -e " $TC|$NC    $BG 8 $NC $E8      $TC|$NC    $BG 9 $NC $E9 $TC|$NC"
		echo -e " $TC|$NC--------------------------------$TC|$NC-------------------------------$TC|$NC"
		echo -e " $TC|$NC    $BG L $NC $(pad_vis "$E10" 24)$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
			set_pointer_speed
			;;
		2)
			echo
			toggle_tap_to_click
			echo
			echo -e "$RED To return press ENTER $NC"
			read -r
			;;
		3)
			echo
			toggle_drag_lock
			echo
			echo -e "$RED To return press ENTER $NC"
			read -r
			;;
		4)
			echo
			toggle_left_handed
			echo
			echo -e "$RED To return press ENTER $NC"
			read -r
			;;
		5)
			echo
			toggle_disable_while_typing
			echo
			echo -e "$RED To return press ENTER $NC"
			read -r
			;;
		6)
			echo
			toggle_natural_scrolling
			echo
			echo -e "$RED To return press ENTER $NC"
			read -r
			;;
		7)
			echo
			toggle_horizontal_scrolling
			echo
			echo -e "$RED To return press ENTER $NC"
			read -r
			;;
		8)
			echo
			if command -v man >/dev/null 2>&1; then
				man xinput
			else
				echo "No man page viewer installed (package man-db). Short help instead:"
				xinput --help 2>&1 | head -20
			fi
			echo
			echo -e "$RED To return press ENTER $NC"
			read -r
			;;
		9)
			echo
			open_url "https://wiki.archlinux.org/title/Touchpad_Synaptics"
			echo
			echo -e "$RED To return press ENTER $NC"
			read -r
			;;
		l | L)
			echo
			gui
			echo
			echo -e "$RED To return press ENTER $NC"
			read -r
			;;
		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

