#! /bin/bash
#
# This initscript was created by Dererk <dererk@debian.org> for martian-modem
#
# Start/stop the martian-modem daemon
### BEGIN INIT INFO
# Provides:          martian-modem
# Required-Start:    $syslog $remote_fs $time
# Required-Stop:     $syslog $remote_fs $time
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Userspace martian-modem session manager
# Description:       This daemon consists in the userspace part that controlles
#                    the martian-modem sessions status.
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/martian_modem
NAME=martian-modem
DESC=martian-modem

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

# Include martian-modem defaults if available
if [ -f /etc/default/martian-modem ] ; then
        . /etc/default/martian-modem
        USE_LOG="--syslog"      
        if [ $USE_SYSLOG = "N" ]; then
                USE_LOG="--log $LOGFILE"
        fi
	DAEMON_OPTS="$USE_LOG --daemon --user=$USER --group=$GROUP --mode=$MODE --debug=$DEBUG_LEVEL $DEVICE" 
else                            
        echo "ERROR: martian-modem configuration file MISSING!"
        exit 1                  
fi

case "$1" in
    start)
	log_begin_msg "Starting $NAME daemon..."
	pid=`pidof $NAME`
	if [ -n "$pid" ] ; then
	      log_begin_msg "Already running."
	      log_end_msg 0
	      exit 0
	fi

	if [ ! -d "/var/run/$NAME" ]; then
		mkdir -p /var/run/$NAME
		chown $USER:root /var/run/$NAME
	fi
	
	start-stop-daemon --start --oknodo --pidfile /var/run/$NAME/$NAME.pid --exec $DAEMON -- $DAEMON_OPTS

	if ! pidof $DAEMON > /var/run/$NAME/$NAME.pid; then
		log_begin_msg "Oops, something went wront. CHECK SYSLOG!"
		exit 1
	fi
	log_end_msg $?
	;;
    stop)
	log_begin_msg "Stopping $NAME daemon..."
	start-stop-daemon --stop --oknodo --pidfile /var/run/$NAME/$NAME.pid --exec $DAEMON
	log_end_msg $?
	rm /var/run/$NAME/$NAME.pid >/dev/null 2>&1
	;;
    force-reload)
	$0 restart
	;;
    restart)
	$0 stop
	$0 start
	;;
    status)
    	if start-stop-daemon --start --test --exec $DAEMON -- $DAEMON_OPTS >/dev/null 2>&1; then
		echo "$NAME is STOPPED!" && exit 1
	else
		echo "$NAME is RUNNING using process id `cat /var/run/$NAME/$NAME.pid`." && exit 0
	fi
	;;		
    *)
	log_success_msg "Usage: /etc/init.d/$NAME {start|stop|status|force-reload|restart}"
	exit 1
	;;
esac

exit 0
