#!/bin/sh
#
# TiMidity      /etc/init.d/ initscript for TiMidity++
#               $Id: timidity.init,v 1.6 2004/09/30 01:04:04 hmh Exp $
#
#               Copyright (c) 2004 by Henrique M. Holschuh <hmh@debian.org>
#               Distributed under the GPL version 2
#               This is a modified version by Lisandro Damián Nicanor
#               Pérez Meyer <perezmeyer@gmail.com>
#

set -e

# Script specific configurations
PATH=/sbin:/bin:/usr/sbin:/usr/bin
DESC="TiMidity++ ALSA midi emulation"
NAME=timidity
DAEMON=/usr/bin/$NAME
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Rest of the configurations
PMIDI=/usr/bin/pmidi
TIM_ALSASEQ=
TIM_ALSASEQPARAMS="-B2,8"
PARAMS="${TIM_ALSASEQPARAMS} -iAD"
START="--start --quiet --exec ${DAEMON} --pidfile ${PIDFILE} -- ${PARAMS}"


# Gracefully exit if the package has been removed.
test -x ${DAEMON} || exit 0
test -x ${PMIDI} && pmidi_enabled="true" || pmidi_enabled="false";

# Read config file if it is present.
#[ -r /etc/default/timidity ] && . /etc/default/timidity
#[ "${TIM_ALSASEQ}" != "true" ] && exit 0


d_start()
{
	[ -d /proc/asound ] ||
	{
		echo -n "(ALSA is not active, cannot start)"
		exit 0
	}
	if start-stop-daemon ${START} >/dev/null; then
		if [ $pmidi_enabled = "true" ] ; then
			sleep 1
			echo -e "\nEmulating midi on ports: ";
			pmidi -l | grep "TiMidity" | cut -f 1 -d ' ' | xargs
		fi
	else
		if start-stop-daemon --test ${START}  >/dev/null 2>&1; then
			echo -n -e "(failed).\n"
			exit 1
		else
			echo -n -e " already running.\n"
			exit 0
		fi
	fi
}

d_stop()
{
	if ! start-stop-daemon --stop --quiet --pidfile ${PIDFILE} \
		--exec ${DAEMON} --retry 10 ; then
		echo -n -e " (failed).\n"
		exit 1
	fi
}


case "$1" in
  start)
		echo -n -e "Starting ${DESC}: $NAME"
		d_start
		echo "Done."
	;;

  stop)
		echo -n -e "Stopping $DESC: $NAME"
		d_stop
		echo " Done."
	;;

  restart|force-reload)
    echo -n -e "Restarting $DESC: $NAME"
    d_stop
    sleep 1
    d_start
    echo " Done."
	;;

  *)
		echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
		exit 1
	;;

esac

exit 0
