#!/bin/sh
# Start, stop and restart a busybox deamon on SliTaz, at boot time or 
# with the command line.
#
# To start daemon at boot time, just put the right name in the $RUN_DAEMONS
# variable of /etc/rcS.conf and configure options with /etc/daemons.conf.
#
. /etc/init.d/rc.functions

NAME=$(basename $0)
DESC="$NAME deamon"
DAEMON=$(which $NAME)
eval $(grep -i ^${NAME}_OPTIONS /etc/daemons.conf | sed 's/.*_OPT/OPT/')
PIDFILE=/var/run/$NAME.pid

active_inetd()
{
if grep $DAEMON /etc/inetd.conf | grep -q ^\#; then
    sed -i "s,^#\(.*$DAEMON.*\)$,\1," /etc/inetd.conf
    /etc/init.d/inetd stop > /dev/null
    exec /etc/init.d/inetd start
else
    echo "$NAME is already active."
    exit 1
fi
}

inactive_inetd()
{
if grep $DAEMON /etc/inetd.conf | grep -q ^\#; then
    echo "$NAME is not active."
    exit 1
else
    sed -i "s,^.*$DAEMON.*$,#&," /etc/inetd.conf
    /etc/init.d/inetd stop > /dev/null
    exec /etc/init.d/inetd start
fi
}

case "$1" in
  start)
    grep -qs $DAEMON /etc/inetd.conf && active_inetd
    if active_pidfile $PIDFILE $NAME ; then
      echo "$NAME is already running."
      exit 1
    fi
    echo -n "Starting $DESC: $NAME... "
    $DAEMON $OPTIONS 
    [ -f $PIDFILE ] || pidof $NAME | awk '{ print $1 }' > $PIDFILE
    active_pidfile $PIDFILE $NAME
    status
    ;;
  stop)
    grep -qs $DAEMON /etc/inetd.conf && inactive_inetd
    if ! active_pidfile $PIDFILE $NAME ; then
      echo "$NAME is not running."
      exit 1
    fi
    echo -n "Stopping $DESC: $NAME... "
    kill `cat $PIDFILE`
    status
    ;;
  restart)
    grep -qs $DAEMON /etc/inetd.conf && exit 0
    if ! active_pidfile $PIDFILE $NAME ; then
      echo "$NAME is not running."
      exit 1
    fi
    echo -n "Restarting $DESC: $NAME... "
    kill `cat $PIDFILE`
    sleep 2
    $DAEMON $OPTIONS
    [ -f $PIDFILE ] || pidof $NAME | awk '{ print $1 }' > $PIDFILE
    active_pidfile $PIDFILE $NAME
    status
    ;;
*)
    echo ""
    echo -e "\033[1mUsage:\033[0m /etc/init.d/`basename $0` [start|stop|restart]"
    echo ""
    exit 1
    ;;
esac

exit 0
