#!/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:          h2o
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Optimized HTTP/1.x, HTTP/2 server
# Description:       Starts and stops h2o, the optimized HTTP/1.x and HTTP/2
#                    server.
### END INIT INFO

# Author: Apollon Oikonomopoulos <apoikos@debian.org>

DESC="Optimized HTTP/1.x, HTTP/2 server"
DAEMON=/usr/bin/h2o
CONFIG=${CONFIG:=/etc/h2o/h2o.conf}
DAEMON_ARGS="-c ${CONFIG} -m daemon"
PIDFILE="$(grep ^pid-file: "$CONFIG" | awk '{ print $2 }')"

# Override reload() and stop(): during start, the h2o main process is replaced
# by the perl start_server script, which breaks process matching.
do_reload () {
        log_daemon_msg "Reloading $DESC configuration files" "$NAME"
        start-stop-daemon --oknodo --stop --signal HUP --quiet \
          --pidfile "$PIDFILE" --exec "/usr/bin/perl"
        log_end_msg $?
}

do_status () {
	status_of_proc ${PIDFILE:+-p ${PIDFILE}} /usr/bin/perl h2o
}

do_stop_cmd () {
        start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 \
            $STOP_ARGS \
            ${PIDFILE:+--pidfile ${PIDFILE}} --exec /usr/bin/perl
        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 \
            --exec $DAEMON
        [ "$?" = 2 ] && return 2
        # Many daemons don't delete their pidfiles when they exit.
        rm -f $PIDFILE
        return $RETVAL
}
