#!/bin/sh
### BEGIN INIT INFO
# Provides:          gitlab-runner
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Should-Start:      $syslog
# Should-Stop:       $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start gitlab-runner at boot time
# Description: gitlab-runner - GitLab Runner
### END INIT INFO

NAME=$(basename $(readlink -f "$0"))
DAEMON=/usr/bin/$NAME
PIDFILE=/var/run/$NAME.pid
DAEMON_USER=root
DAEMON_GROUP=root
DAEMON_ARGS="run --working-directory /var/lib/gitlab-runner --config /etc/gitlab-runner/config.toml --service gitlab-runner --syslog --user gitlab-runner"

# Exit if executable is not installed
[ -x "$DAEMON" ] || exit 0

# Read configuration variable file if it is present
[ -r /etc/default/$NAME ] && . /etc/default/$NAME

RETRY=TERM/30/KILL/5

# Load the VERBOSE setting and other rcS variables
[ -f /etc/default/rcS ] && . /etc/default/rcS

# Define LSB log_* functions.
. /lib/lsb/init-functions || exit 1

_ev_ () {
  local rv_=$?
  [ "$VERBOSE" = "no" ] || eval $@
  return $rv_
}

case "$1" in
    start)
        _ev_ log_action_begin_msg \"Starting $NAME\"
        if R=$($0 status); then
            _ev_ log_action_end_msg 0 \"$R\"
        else
            R=$(start-stop-daemon --start --pidfile $PIDFILE --make-pidfile --background \
                --chuid $DAEMON_USER --exec $DAEMON -- $DAEMON_ARGS)
            sleep 1
            $0 status >>/dev/null
            _ev_ log_action_end_msg $? \"$R\"
        fi
    ;;
    debug)
        start-stop-daemon --start --exec $DAEMON --chuid $DAEMON_USER -- --debug $DAEMON_ARGS
    ;;
    stop)
        _ev_ log_action_begin_msg \"Stopping $NAME\"
        R=$(start-stop-daemon --stop --oknodo --user $DAEMON_USER --pidfile $PIDFILE --remove-pidfile --retry=$RETRY 2>&1)
        _ev_ log_action_end_msg $? \"$R\"
    ;;
    status)
        ## return status 0 if process is running.
        status_of_proc -p $PIDFILE "$DAEMON" "$NAME"
    ;;
    reload)
        _ev_ log_action_begin_msg \"Reloading $NAME configuration\"
        killproc -p $PIDFILE "$DAEMON" SIGHUP
#        start-stop-daemon --stop --signal HUP --pidfile "${PIDFILE}" --quiet
        _ev_ log_action_end_msg $? \"$R\"
    ;;
    restart|force-reload)
        $0 stop
        $0 start
    ;;
    *)
        log_action_msg "Usage: /etc/init.d/$NAME {start|stop|restart|force-reload|reload|status}"
    ;;
esac
