#!/bin/sh
# Didier Spaier didieratslintdotfr 2019-2022
# I wrote this script from scratch and put it in the public domain as
# stated in https://unlicense.org/
export TEXTDOMAIN=slint-scripts
if [ "$(id -u)" -eq 0 ]; then
	gettext "Please run this script as regular user."; echo
	exit
fi
program_name=$0
features='emacspeak
speechd-el'
desc_emacsspeak=$(gettext "emacspeak (The Complete Audio Desktop, based on emacs)")
desc_speechdel=$(gettext "speechd-el (Emacs client to speech synthesizers and Braille displays)")
descriptions="$desc_emacsspeak
$desc_speechdel"

emacspeak_cmd='(load-file "/usr/share/emacs/site-lisp/emacspeak/lisp/emacspeak-setup.el")'
speechd_el_cmd="(setq speechd-out-active-drivers '(ssip ))
(autoload 'speechd-speak \"speechd-speak\" nil t)
(speechd-speak)"
usage() {
  gettext "Usage: "
  printf '%s' "$program_name <emacspeak> "
  gettext "or"
  echo  " <speechd-el>"
  gettext "This script allows to enable:"; echo
  echo "$descriptions"
  exit
}
if [ $# -ne 1 ]; then usage; fi
if  ! echo "$features"|grep -qw "$1"; then
	printf '%s' "$1 "
	gettext "is an unknown feature."; echo
	gettext "Available features:"; echo
	echo "$descriptions"
	exit
fi
case $1 in
	emacspeak)
		if [ "$(find /var/lib/pkgtools/packages/ -name "${1}*")" = "" ]; then
			printf '%s' "$1 "
			gettext "is not installed."; echo
			exit
		fi
		if ! grep -q emacspeak-setup.el ~/.emacs 2>/dev/null; then
			if [ ! -s  ~/.emacs ]; then
				echo "$emacspeak_cmd" >> ~/.emacs
			else
				bof=$(mktemp)
				bif=$(mktemp)
				sed '/emacspeak-setup.el/d
				/speechd-speak/d
				/speechd-out-active-drivers/d
				/setenv "DTK_PROGRAM" "outloud"/d' ~/.emacs > "$bif"
				echo "$emacspeak_cmd" > "$bof"
				cat "$bof" "$bif" > ~/.emacs
				rm "$bof" "$bif"
			fi
		fi
		gettext "emacspeak is enabled and speechd-el is disabled, as they are mutually exclusive."; echo
		if [ "$(find /var/lib/pkgtools/packages/ -name "voxin*")" ]; then
			bof=$(mktemp)
			bif=$(mktemp)
			cp ~/.emacs "$bif"
			sed '/setenv "DTK_PROGRAM" "outloud"/d' ~/.emacs > "$bif"
			gettext "Do you want to use a voxin voice with emacspeak? [Y/n] "
			read -r dummy
			if [ ! "$dummy" = "n" ] && [ ! "$dummy" = "N" ]; then
				echo '(setenv "DTK_PROGRAM" "outloud")' > "$bof"
				cat "$bof" "$bif" > ~/.emacs
				rm "$bof" "$bif"
			else
				mv "$bif" ~/.emacs
			fi
		fi
	;;
	speechd-el)
		if [ "$(find /var/lib/pkgtools/packages/ -name "${1}*")" = "" ]; then
			printf '%s' "$1 "
			gettext "is not installed."; echo
			exit
		fi
		if ! grep -q speechd-speak ~/.emacs 2>/dev/null; then
			if [ ! -s  ~/.emacs ]; then
				echo "$speechd_el_cmd" >> ~/.emacs
			else
				bof=$(mktemp)
				bif=$(mktemp)
				cp "$bof" "$bif"
				sed '/emacspeak-setup.el/d
				/setenv "DTK_PROGRAM" "outloud"/d' ~/.emacs > "$bif"
				echo "$speechd_el_cmd" > "$bof"
				cat "$bof" "$bif" > ~/.emacs
				rm "$bof" "$bif"
			fi
		fi
		gettext "speechd-el is enabled and emacspeak is disabled, as they are mutually exclusive."; echo
	;;
esac
