#!/bin/sh
# kFreeBSD do not accept scripts as interpreters, using #!/bin/sh and sourcing.
if [ true != "$INIT_D_SCRIPT_SOURCED" ] ; then
    set "$0" "$@"; INIT_D_SCRIPT_SOURCED=true . /lib/init/init-d-script
fi
### BEGIN INIT INFO
# Provides:          goiardi
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Goiardi Chef server
# Description:       Goiardi is an implementation of the Chef server written in
#                    Go. It can either run entirely in memory, with the option
#                    to save and load the in-memory data and search indexes to
#                    and from disk, or it can use PostgreSQL or MariaDB/MySQL
#                    as its storage backend.
### END INIT INFO

# Author: Jordi Mallach <jordi@debian.org>

DESC="Goiardi Chef server"
DAEMON=/usr/bin/goiardi
DAEMONUSER=goiardi
DAEMONGROUP=goiardi
DAEMON_ARGS="-c /etc/goiardi/goiardi.conf"
PIDFILE="/run/goiardi.pid"

# Return
#   0 if daemon has been started
#   1 if daemon was already running
#   2 if daemon could not be started
do_start_cmd() {
	start-stop-daemon --start --quiet ${PIDFILE:+--pidfile ${PIDFILE}} \
	    --background --make-pidfile \
	    $START_ARGS --user $DAEMONUSER --group $DAEMONGROUP \
	    --startas $DAEMON --name $NAME --exec $DAEMON --test > /dev/null \
	    || return 1
	start-stop-daemon --start --quiet ${PIDFILE:+--pidfile ${PIDFILE}} \
	    --background --make-pidfile \
	    $START_ARGS --user $DAEMONUSER --group $DAEMONGROUP \
	    --startas $DAEMON --name $NAME --exec $DAEMON -- $DAEMON_ARGS \
	    || return 2
	# Add code here, if necessary, that waits for the process to be ready
	# to handle requests from services started subsequently which depend
	# on this one.  As a last resort, sleep for some time.
}

# Return
#   0 if daemon has been stopped
#   1 if daemon was already stopped
#   2 if daemon could not be stopped
#   other if a failure occurred
do_stop_cmd() {
	start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 \
	    --make-pidfile \
	    $STOP_ARGS \
	    ${PIDFILE:+--pidfile ${PIDFILE}} --name $NAME --exec $DAEMON
	RETVAL="$?"
	[ "$RETVAL" = 2 ] && return 2
	# Wait for children to finish too if this is a daemon that forks
	# and if the daemon is only ever run from this initscript.
	# If the above conditions are not satisfied then add some other code
	# that waits for the process to drop all resources that could be
	# needed by services started subsequently.  A last resort is to
	# sleep for some time.
	start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 \
	    $STOP_ARGS --user $DAEMONUSER --group $DAEMONGROUP \
	    --exec $DAEMON
	[ "$?" = 2 ] && return 2
	# Many daemons don't delete their pidfiles when they exit.
	rm -f $PIDFILE
	return $RETVAL
}
