#!/bin/bash

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

browser=''
printers=''
STATUSVAR=1

# =======================
# Service messages section
# Wrong Option
ERRORMSG="$RED Wrong option $NC"
TRYAGAINMSG=" Please try again..."
#
CONTINMSG="$RED To return press ENTER $NC"
XSANEINSTMSG="No scanner interface is installed and pacman seems to be in use"
NEEDSANEMSG="A scanner needs the sane backend. Installing simple-scan with sane."
SELECTDEFAULTPRINTERMSG="Select new default printer"
DEFAULTPRINTERSETMSG="The new default printer has been set"
SELECTFILESFORPRINTMSG="Select the files to print (use TAB to mark files for printing)"
SELECTPRINTERTOUSEMSG="Select the printer to use"
PRINTINGMSG="Printing now"
SELECTDEFAULTSCANNERMSG="Searching for scanners... Select new default"
IMGFILETYPECHOOSEMSG="Which filetype should be used? "
NAMEFORSCANNEDFILEMSG="What name shall be given to the scanned file?"

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

# CUPS is an optional dependency
function require_cups() {
	if [ -x "$(command -v lpstat)" ]; then
		return 0
	fi
	echo "CUPS is not installed. Install it with: sudo pacman -Syu cups"
	return 1
}

# Scanning needs sane, not CUPS
function require_scanner() {
	if [ -x "$(command -v scanimage)" ]; then
		return 0
	fi
	echo "The scanner tools are not installed. They come from sane: sudo pacman -Syu sane"
	return 1
}

# `lpstat -o` is the only rc that separates a running scheduler from a stopped one
function cups_scheduler_running() {
	require_cups || return 1
	lpstat -o >/dev/null 2>&1
}

# Read the queue list. rc 0 means the scheduler answered
function read_cups_queues() { # sets printers and cups_list
	require_cups || return 1
	if ! cups_scheduler_running; then
		echo "CUPS is installed but its scheduler is not running, so nothing can be printed."
		echo "Start it with: sudo systemctl start cups"
		return 1
	fi
	# Only lines starting with `printer <name>` are queues
	cups_list=$(lpstat -p -d 2>/dev/null)
	printers=$(printf '%s\n' "$cups_list" | awk '/^printer / {print $2}')
	return 0
}

# Does the entry have a queue to work with?
function require_printer_queue() {
	read_cups_queues || return 1
	if [ -z "$printers" ]; then
		echo "No printer queue is configured here. Add one in the CUPS web interface (entry 1)."
		return 1
	fi
	return 0
}

# A scanned file name goes into a redirect, so slashes and a leading dash are refused
function valid_scan_name() {
	case "$1" in
	"" | -* | */*)
		echo "Not a usable file name: '$1'. No slash, no leading dash."
		return 1
		;;
	esac
	return 0
}

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

# Ask the name as a whole line; an empty answer is asked again
function ask_scan_name() { # -> sets filename
	local empty=0
	while true; do
		echo "$NAMEFORSCANNEDFILEMSG"
		if ! read -r filename; then
			# A last line without a trailing newline still carries the answer
			[ -n "$filename" ] && return 0
			filename=""
			return 1
		fi
		if [ -n "$filename" ]; then
			return 0
		fi
		echo "No name given yet."
		if ! [ -t 0 ]; then
			empty=$((empty + 1))
			[ "$empty" -lt 3 ] || return 1
		fi
	done
}

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

function scanner_interface() {
	if [ -x "$(command -v xsane)" ]; then
		xsane
		STATUSVAR=$?
	elif [ -x "$(command -v simple-scan)" ]; then
		simple-scan
		STATUSVAR=$?
	else
		if [ -e /var/lib/pacman/db.lck ]; then
			echo "$XSANEINSTMSG"
			STATUSVAR=1
		else
			echo "$NEEDSANEMSG"
			$INSTALLPKGS sane simple-scan && simple-scan
			STATUSVAR=$?
		fi
	fi
	return $STATUSVAR
}

function detect_browser() {
	for b in elinks links w3m lynx; do
		if [ -x "$(command -v $b)" ]; then
			echo "$b"
			return 0
		fi
	done
	echo ""
	return 1
}

function webinterface() {
	# The web interface needs a running scheduler, not only the lpstat command
	read_cups_queues || {
		STATUSVAR=1
		return $STATUSVAR
	}
	browser=$(detect_browser)
	if [ -z "$browser" ]; then
		if [ -e /var/lib/pacman/db.lck ]; then
			echo "No cli browser installed and Pacman seems to be in use"
			return 1
		fi
		echo "Installing links to open the CUPS web interface"
		browser="links"
		$INSTALLPKGS links || return 1
	fi
	$browser http://localhost:631
	STATUSVAR=$?
	return $STATUSVAR
}

function set_default_printer() {
	require_printer_queue || {
		STATUSVAR=1
		return $STATUSVAR
	}
	pick=$(printf '%s\n' "$printers" | fzf -e --reverse --prompt="$SELECTDEFAULTPRINTERMSG >")
	if [ -z "$pick" ]; then
		STATUSVAR=1
		return $STATUSVAR
	fi
	lpoptions -d "$pick"
	STATUSVAR=$?
	if [ $STATUSVAR -eq 0 ]; then
		echo ""
		echo ""
		echo "$DEFAULTPRINTERSETMSG"
	fi
	return $STATUSVAR
}

function print_file() {
	require_printer_queue || {
		STATUSVAR=1
		return $STATUSVAR
	}
	# One argument per file, no word splitting
	files=()
	while read -r f; do
		[ -n "$f" ] && files+=("$f")
	done < <(fzf -m --reverse --prompt=" $SELECTFILESFORPRINTMSG >")
	if [ ${#files[@]} -eq 0 ]; then
		STATUSVAR=1
		return $STATUSVAR
	fi
	# A path starting with a dash is an option for lpr, so it goes over as ./<path>
	args=()
	for f in "${files[@]}"; do
		case "$f" in
		-*) args+=("./$f") ;;
		*) args+=("$f") ;;
		esac
	done
	if [ -e "$HOME/.cups/lpoptions" ] && grep -q "Default" "$HOME/.cups/lpoptions"; then
		lpr "${args[@]}"
	else
		printer=$(printf '%s\n' "$printers" | fzf -e --reverse --prompt="$SELECTPRINTERTOUSEMSG >")
		if [ -z "$printer" ]; then
			STATUSVAR=1
			return $STATUSVAR
		fi
		lpr -P "$printer" "${args[@]}"
	fi
	STATUSVAR=$?
	if [ $STATUSVAR -eq 0 ]; then
		echo ""
		echo ""
		echo "$PRINTINGMSG"
		sleep 3
	fi
	return $STATUSVAR
}

# Scans into a name the user typed, with the sane default device
function default_scan() {
	require_scanner || {
		STATUSVAR=1
		return $STATUSVAR
	}
	if ! ask_scan_name; then
		STATUSVAR=1
		return $STATUSVAR
	fi
	if valid_scan_name "$filename"; then
		filetype=$(select_filetype)
		if [ "$filetype" != "" ]; then
			# The extension is added here, so a name that already carries one is kept
			case "$filename" in
			*.$filetype) target="$filename" ;;
			*) target="$filename.$filetype" ;;
			esac
			# The scan goes into a redirect, which truncates first
			if [ -e "$target" ]; then
				echo "$target already exists. Choose another name, or delete it first."
				STATUSVAR=1
				return $STATUSVAR
			fi
			scanimage -p --format="$filetype" >"$target"
			STATUSVAR=$?
		else
			STATUSVAR=1
		fi
	else
		STATUSVAR=1
	fi
	return $STATUSVAR
}

# The device line is written into ~/.profile once
function set_default_scanner() {
	require_scanner || {
		STATUSVAR=1
		return $STATUSVAR
	}
	default_scanner=$(scanimage -L 2>/dev/null |
		fzf -e --reverse --prompt="$SELECTDEFAULTSCANNERMSG >" |
		awk '{print $2}' | sed -e "s/^'//" -e "s/'$//")
	# fzf can end with nothing: that is a cancel, not a success
	if [ -z "$default_scanner" ] ||
		[ "$(printf '%s\n' "$default_scanner" | wc -l)" -ne 1 ]; then
		STATUSVAR=1
		return $STATUSVAR
	fi
	case "$default_scanner" in
	*"|"* | *"&"* | *"\""* | *"\\"*)
		# The value goes into an export line, so |, &, a quote and a backslash are refused
		echo "Not a usable device name: $default_scanner"
		STATUSVAR=1
		return $STATUSVAR
		;;
	esac
	if grep -q '^export SANE_DEFAULT_DEVICE=' "$HOME/.profile" 2>/dev/null; then
		cp "$HOME/.profile" "$HOME/.profile.bak" || {
			echo "The backup of $HOME/.profile failed, nothing was changed."
			STATUSVAR=1
			return 1
		}
		sed -i "s|^export SANE_DEFAULT_DEVICE=.*|export SANE_DEFAULT_DEVICE=\"$default_scanner\"|" "$HOME/.profile"
	else
		printf 'export SANE_DEFAULT_DEVICE="%s"\n' "$default_scanner" >>"$HOME/.profile"
	fi
	STATUSVAR=$?
	# Exported, so this run already uses the new device
	export SANE_DEFAULT_DEVICE="$default_scanner"
	return $STATUSVAR
}

function select_filetype() {
	PS3="$IMGFILETYPECHOOSEMSG"
	# Gather the results in an array. "cancel" is needed here
	filetypes=("pnm" "tiff" "png" "jpeg" "cancel")

	select pick in "${filetypes[@]}"; do
		case $pick in
		cancel)
			echo ""
			break
			;;
		"")
			continue
			;;
		*)
			echo "$pick"
			break
			;;
		esac
	done
}

function main() {

	# Define Menu entries which will be run with the echo command
	E0="\e[1mQ\e[0muit"
	E1="Manage Printers"
	E2="Print Files"
	E3="Set Default Printer"
	E4="List Printers"
	E5="Set Default Scanner"
	E6="Scan With GUI"
	E7="List Scanners"
	E8="Scan Using Defaults"

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

		echo
		echo -e "                       $BG$TC Printers and Scanners $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"
		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
			webinterface
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		2)
			echo
			print_file
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		3)
			echo
			set_default_printer
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		4)
			echo
			read_cups_queues && printf '%s\n' "$cups_list"
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		5)
			echo
			set_default_scanner
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		6)
			echo
			scanner_interface
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		7)
			echo
			require_scanner && scanimage -L 2>/dev/null
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				pressanykeyrequest
			else
				echo ""
			fi
			;;
		8)
			echo
			default_scan
			STATUSVAR=$?
			if [ $STATUSVAR -eq 0 ]; then
				pressanykeyrequest
			else
				echo ""
			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
