#!/bin/sh
# Didier Spaier <didier~at~slint.fr> 2019
# I wrote this script from scratch and put it in the public domain.
if [ $(id -u) -eq 0 ]; then
	echo "Please run this script as regular user."
	exit
fi
features='emacspeak
speechd-el'
descriptions=\
'emacspeak (The Complete Audio Desktop, based on emacs)
speechd-el (Emacs client to speech synthesizers and Braille displays)'

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() {
  echo "Usage: $0 <emacspeak> or <speechd-el>"
  echo "This script allows to enable:"
  echo "$descriptions"
  exit
}
if [ $# -ne 1 ]; then usage; fi
if  ! echo $features|grep -qw $1; then
	echo "$1 is an unknown feature."
	echo "Available features:"
	echo "$descriptions"
	exit
fi
case $1 in
	emacspeak)
		if [ "$(find /var/log/packages/ -name "${1}*")" = "" ]; then
			echo "$1 is not installed"
			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
		echo "emacspeak is enabled and speechd-el is disabled, as they are mutually exclusive."
		if [ "$find(/var/log/packages/ -name "voxin*")" ]; then
			bof=$(mktemp)
			bif=$(mktemp)
			cp ~/.emacs $bif
			sed '/setenv "DTK_PROGRAM" "outloud"/d' ~/.emacs > $bif
			printf "Do you want to use a voxin voice with emacspeak? [Y/n] "
			read 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/log/packages/ -name "${1}*")" = "" ]; then
			echo "$1 is not installed."
			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
		echo "speechd-el is enabled and emacspeak is disabled, as they are mutually exclusive."
	;;
esac
