#! /bin/sh

### BEGIN INIT INFO
# Provides:          mythexport 
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start/Stop the MythExport Daemon.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/mythexport-daemon
NAME="mythexport"
COMMAND=/usr/bin/perl
ARGS=""
DESC="MythExport Daemon"

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

set -e

USER=mythtv
USER_HOME=$(grep ^$USER /etc/passwd | awk -F : '{print $6}')
RUNDIR=/var/run/mythtv
NICE=0

mkdir -p $RUNDIR
chown -R $USER $RUNDIR

unset DISPLAY
unset SESSION_MANAGER

case "$1" in
  start)
	if [ -e $RUNDIR/$NAME.pid ]; then
		PIDDIR=/proc/$(cat $RUNDIR/$NAME.pid)
		if [ -d ${RUNDIR} -a "$(readlink -f ${PIDDIR}/exe)" = "${COMMAND}" ]; then
			log_success_msg "$DESC already started; use restart instead."
			exit 0
		else
			log_success_msg "Removing stale PID file $RUNDIR/$NAME"
			rm -f $RUNDIR/$NAME.pid
		fi
	fi
	log_daemon_msg "Starting $DESC: $NAME "
	start-stop-daemon --start --pidfile $RUNDIR/$NAME.pid \
		--chuid $USER --nicelevel $NICE --exec $COMMAND --startas $DAEMON $ARGS
	log_end_msg $?
	;;
  stop)
	log_daemon_msg "Stopping $DESC: $NAME "
	start-stop-daemon --stop --oknodo --pidfile $RUNDIR/$NAME.pid \
		--chuid $USER --exec $COMMAND --startas $DAEMON $ARGS
	log_end_msg $?
	test -e $RUNDIR/$NAME.pid && rm $RUNDIR/$NAME.pid
	;;
  restart|force-reload)
	log_daemon_msg "Restarting $DESC: $NAME "
	start-stop-daemon --stop --oknodo --pidfile $RUNDIR/$NAME.pid \
                --chuid $USER --exec $COMMAND --startas $DAEMON $ARGS
	sleep 3
	start-stop-daemon --start --pidfile $RUNDIR/$NAME.pid \
                --chuid $USER --nicelevel $NICE --exec $COMMAND --startas $DAEMON $ARGS
    log_end_msg $?
	;;
  status)
	# We want to maintain backward compatibility with Hardy,
	# so we're not going to use status_of_proc()
	pidofproc -p $RUNDIR/$NAME.pid $DAEMON >/dev/null && status=0 || status=$?
	if [ $status -eq 0 ]; then
		log_success_msg "$NAME is running"
	else
		log_failure_msg "$NAME is not running"
	fi
	exit $status
	;;
  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|force-reload|status}" >&2
	exit 2
	;;
esac

exit 0
