#!/bin/bash
#
# init-example
#
# chkconfig:   2345 98 20
# description: init-example
# processname: init-example
# config: /etc/sysconfig/init-example
# pidfile: /var/run/init-example.pid

# source function library
. /etc/rc.d/init.d/functions

prog="init-example"
user="init-example"
exec="/bin/node"
exec_opts="/opt/init-example/hello.js"
confdir="/etc/sysconfig"
pidfile="/var/run/$prog.pid"
lockfile="/var/lock/subsys/$prog"
logfile="/var/log/$prog.log"
umask_opts="077" # 022, 077
ulimit_opts="-n 64000 -u 64000"

# pull in sysconfig settings
[ -e $confdir/$prog ] && . $confdir/$prog

start() {
    umask $umask_opts
    ulimit $ulimit_opts

    touch $logfile $pidfile
    chown $user:$user $logfile $pidfile

    echo -n $"Starting $prog: "

    daemon \
        --pidfile=$pidfile \
        --user=$user \
        " { $exec ${exec_opts} &>> $logfile & } ; echo \$! >| $pidfile "

    RETVAL=$?
    echo

    [ $RETVAL -eq 0 ] && touch $lockfile

    return $RETVAL
}

stop() {
    echo -n $"Shutting down $prog: "
    ## graceful shutdown with SIGINT
    killproc -p $pidfile $exec -INT
    RETVAL=$?
    echo
    [ $RETVAL -eq 0 ] && rm -f $lockfile $pidfile
    return $RETVAL
}

restart() {
    stop
    sleep 1
    start
}

reload() {
    restart
    #echo -n $"Reloading $prog: "
    #killproc -p $pidfile $exec -HUP
    #echo
}

force_reload() {
    restart
}

rh_status() {
    status -p "$pidfile" -l $prog $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
        restart
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
        exit 2
esac

exit $?
