#!/bin/sh
### BEGIN INIT INFO
# Provides:          mumudvb
# Required-Start:    $remote_fs $network $syslog
# Required-Stop:     $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: mumudvb
# Description:       Digital television streaming program
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/mumudvb
PIDDIR=/var/run/mumudvb
DEFAULT_FILE=/etc/default/mumudvb
NAME=mumudvb
DESC="television streaming program"

#Reading of the config file
if [ -f "$DEFAULT_FILE" ] ; then
        . "$DEFAULT_FILE"
fi

if [ "$DONTSTARTMUMU" = "true" ]; then exit 0; fi

. /lib/lsb/init-functions

test -x $DAEMON || exit 5

set -e

do_start() {
        if [ ! -d $PIDDIR ]; then
                mkdir -p $PIDDIR
        fi
        chown $DAEMONUSER $PIDDIR
	if [ -x "$LAUNCH_BEFORE_MUMU" ]; then
		log_daemon_msg "Launching pre script ..."
		eval $LAUNCH_BEFORE_MUMU
		log_daemon_msg "Done."
	fi
	for ADAPTER in $ADAPTERS; do
		#Todo : fails if all card fails
		log_daemon_msg " Starting card $ADAPTER"
		eval CONFIG_FILE=\$MUMUDVB_CONF_$ADAPTER
		if [ ! -f $CONFIG_FILE ]; then
                   log_warning_msg " Card $ADAPTER: Config file $CONFIG_FILE not found."
		else
		   start-stop-daemon --start --oknodo --pidfile "$PIDDIR/mumudvb_carte$ADAPTER.pid"\
               		 --chuid $DAEMONUSER --exec $DAEMON -- $DAEMON_OPTS --card $ADAPTER -c $CONFIG_FILE
		fi
	done
}

do_stop() {
	for PIDFILE in `ls $PIDDIR/mumudvb_carte*.pid 2> /dev/null`; do
	        start-stop-daemon --stop --oknodo --pidfile "$PIDFILE" \
        	        --exec $DAEMON
	done
}

case "$1" in
  start)
        if [ ! -f "$DEFAULT_FILE" ]; then
                log_failure_msg "$DEFAULT_FILE not found, Can't start $NAME"
                exit 6
        fi

        log_daemon_msg "Starting $DESC: $NAME"
        do_start
        log_end_msg $?
        ;;
  stop)
        log_daemon_msg "Stopping $DESC: $NAME"
        do_stop
        log_end_msg $?
        ;;
  restart|force-reload)
        log_daemon_msg "Restarting $DESC: $NAME"
        do_stop
        sleep 1
        do_start
        log_end_msg $?
        ;;
  status)
        status_of_proc "$DAEMON" "$DESC: $NAME" && exit 0 || exit $?
        ;;
  *)
        log_success_msg "Usage: $0 {start|stop|restart|force-reload|status}" >&2
        exit 1
        ;;
esac

exit 0
