#!/bin/sh
#
# ${{app_name}} <${{app_name}}>
#
# chkconfig: 2345 20 80
# description: ${{descr}}
#

### BEGIN INIT INFO
# Provides: ${{app_name}}
# Required-Start: ${{start_facilities}}
# Required-Stop: ${{stop_facilities}}
# Default-Start: ${{start_runlevels}}
# Default-Stop: ${{stop_runlevels}}
# Should-Start:
# Should-Stop:
# Short-Description: ${{descr}}
# Description: ${{descr}}
### END INIT INFO

### -----------------
# This script was created using following sources
#
# http://stackoverflow.com/questions/8124345/call-to-daemon-in-a-etc-init-d-script-is-blocking-not-running-in-background
# https://fedoraproject.org/wiki/Packaging:SysVInitScript#Initscript_template
### -----------------

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

# Source from package defined config. Defaults to,
# bashScriptEnvConfigLocation := Some("/etc/default/" + (packageName in Linux).value)
[ -e ${{env_config}} ] && . ${{env_config}}

# Source from sysconfig
# This order means system config appends/overrides package config
[ -e /etc/sysconfig/${{app_name}} ] && . /etc/sysconfig/${{app_name}}

exec="${{chdir}}/bin/${{exec}}"
prog="${{app_name}}"
lockfile="/var/lock/subsys/${{app_name}}"

RUN_CMD="$exec >> /var/log/${{app_name}}/daemon.log 2>&1 &"

# $JAVA_OPTS used in $exec wrapper
export JAVA_OPTS

[ -z "${DAEMON_USER:-}" ] && DAEMON_USER=${{daemon_user}}

# If program manages its own PID file then it
# should declare its location in PIDFILE
if [ -z "${PIDFILE:-}" ]; then
    PIDFILE=/var/run/${{app_name}}/running.pid
    # echo $! must run in the shell started by `runuser` in `daemon`
    RUN_CMD="$RUN_CMD echo \$! > $PIDFILE"
fi

start() {
    [ -x $exec ] || exit 5
    echo -n $"Starting $prog: "
    daemon --check $prog --user $DAEMON_USER --pidfile $PIDFILE "$RUN_CMD"
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
}

stop() {
    echo -n $"Stopping $prog: "
    killproc -p $PIDFILE $prog
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
}

restart() {
    stop
    start
}

reload() {
    restart
}

force_reload() {
    restart
}

rh_status() {
    # run checks to determine if the service is running or use generic status
    status -p $PIDFILE -l $lockfile $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 || exit 7
	$1
	;;
    force-reload)
	force_reload
	;;
    status)
	rh_status
	;;
    condrestart|try-restart)
	rh_status || exit 0
	restart
	;;
    *)
	echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}"
	exit 2
esac
exit $?
