#!/bin/sh

# speechd-server-spawn - A script to help with the launching of the
# speech-dispatcher server either per user, or at the system level.
#
# Copyright (C) 2009 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

pidof_current_user()
{
	local spduid userid

	if [ $(id -u) -eq 0 ]; then
		userid=$(getent passwd speech-dispatcher | cut -f 3 -d :)
	else
		userid=$(id -u)
	fi

	for spduid in $(ps -C speech-dispatcher -o uid= | awk '{print $1}')
	do
		if [ "$spduid" = "$userid" ]; then
			echo $(ps -C speech-dispatcher -o uid=,pid= | grep $spduid | awk '{print $2}')
		fi
	done

}

autospawn_check()
{
	if [ $(id -u) -eq 0 ]; then
		if grep '^# AutoSpawn$' /etc/speech-dispatcher/speechd.conf > /dev/null 2>&1 ; then
			return 0
		else
			return 1
		fi
	else
		# If the user has no speech-dispatcher configuration files, assume autospawning = yes.
		if [ ! -f $HOME/.speech-dispatcher/conf/speechd.conf ]; then
			return 0
		else
			if grep '^# AutoSpawn$' $HOME/.speech-dispatcher/conf/speechd.conf > /dev/null 2>&1 ; then
				return 0
			else
				return 1
			fi
		fi
	fi
}


if [ "$(pidof_current_user)" = "" ]; then
	SYSTEM_SPEECHD_SERVER_START_COMMAND="/etc/init.d/speech-dispatcher start spawn > /dev/null 2>&1"

	if [ $(id -u) -eq 0 ]; then
		if autospawn_check ; then
			$SYSTEM_SPEECHD_SERVER_START_COMMAND
			echo $(pidof_current_user)
			exit
		fi
	else
		if [ ! -f $HOME/.speech-dispatcher/conf/speechd.conf ]; then
			mkdir -p $HOME/.speech-dispatcher/conf
			cp -r /etc/speech-dispatcher/* $HOME/.speech-dispatcher/conf
		fi
		if autospawn_check ; then
			speech-dispatcher > /dev/null 2>&1
			echo $(pidof_current_user)
			exit
		fi
	fi
else
	echo $(pidof_current_user)
	exit
fi
