#!/bin/bash
#
# This script can be run anytime to restore speech to a working state on a system.  
# Speech currently is often broken by system updates from Ubuntu. To run the script
# type: 'sudo restorespeech'.

LOGFILE=/dev/null
if [ "$1" = "-l" ]; then
    shift
    if [ $# -lt 1 ]; then
	echo "Expecting log file name"
	exit 1
    fi
    LOGFILE=$1
    shift
fi

if [ $# != 0 ]; then
    echo "Usage: restorespeech [-l logFile]"
    exit 1
fi

# Set pulseaudio to run as system-wide daemon.
echo "Setting pulseaudio to run system-wide"
sed -i 's/PULSEAUDIO_SYSTEM_START=0/PULSEAUDIO_SYSTEM_START=1/' /etc/default/pulseaudio
sed -i 's/^ *; *autospawn *= *yes *$/autospawn = no/' /etc/pulse/client.conf
rm -f /etc/xdg/autostart/pulseaudio.desktop
sed -i 's/^OnlyShowIn=XFCE;$/OnlyShowIn=GNOME;XFCE;/' /etc/xdg/autostart/gnome-volume-control-applet.desktop
sed -i 's/load-module module-native-protocol-unix$/load-module module-native-protocol-unix auth-anonymous=1/' /etc/pulse/system.pa
if [ "`grep 'sleep 4' /etc/init.d/pulseaudio`" = "" ]; then
    sed -i 's/\tstart-stop-daemon\(.*\)--start/\tsleep 4\n\tstart-stop-daemon\1--start/' /etc/init.d/pulseaudio
fi

# Rebuild speakup from source
echo "Rebuilding speakup from source.  This can take a minute or so."
apt-get install -y module-assistant >> $LOGFILE
echo y | m-a a-i -f speakup-source -q >> $LOGFILE 2>&1
modprobe speakup_soft

# Install speechd-up
if [ -f /etc/init.d/speechd-up ]; then
    /etc/init.d/speechd-up stop >> $LOGFILE
fi
apt-get install -y speechd-up >> $LOGFILE

# Enable speech-dispatcher to run system-wide
sed -i 's/RUN_SPEECHD=no/RUN_SPEECHD=yes/' /etc/default/speech-dispatcher

# Edit speechd.conf to enable ibmtts.
sed -i 's/#AddModule "ibmtts"/#AddModule "ibmtts"/' /etc/speech-dispatcher/speechd.conf

# Setup YASR
apt-get install -y yasr >> $LOGFILE
sed -i 's/^synthesizer=emacspeak server/#synthesizer=emacspeak server/
    s/^#synthesizer=speech dispatcher/synthesizer=speech dispatcher/
    s/^#synthesizer port=127.0.0.1:6560/synthesizer port=127.0.0.1:6560/
    s/^key echo=off/key echo=keys/' /etc/yasr/yasr.conf

# Enable brltty for Braille displays
sed -i 's/^RUN_BRLTTY=.*/RUN_BRLTTY=yes/' /etc/default/brltty

# Needed to enable Orca to access root applications
if [ "`grep 'ORBIT_SOCKETDIR XDG_SESSION_COOKIE GTK_MODULES' /etc/sudoers`" = "" ]; then
    sed -i -e 's/# Host alias specification/Defaults\tenv_keep = "ORBIT_SOCKETDIR XDG_SESSION_COOKIE GTK_MODULES"\n\n# Host alias specification/g' /etc/sudoers
fi

