#!/bin/sh
#
# gitlab-runner GitLab Runner
#
# chkconfig:	345 20 80
# description:	Enables automatic start of runners at boot time in the background
# processname:	gitlab-runner

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

DESC="GitLab Runner"
USER="gitlab-runner"
GROUP="gitlab-runner"
CHDIR="/var/lib/gitlab-runner"
NAME="gitlab-runner"
DAEMON="/usr/bin/gitlab-runner"
PIDFILE="/var/run/gitlab-runner.pid"
LOGFILE="/var/log/gitlab-runner.log"

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

do_start() {
	start-stop-daemon --start \
		--pidfile "$PIDFILE" \
		--chdir "$CHDIR" \
		--make-pidfile \
		--chuid "$USER:$GROUP" \
		--exec "$DAEMON" -- "run" >> $LOGFILE 2>&1 &
}

do_stop() {
	start-stop-daemon --stop --pidfile "$PIDFILE" --user "$USER" --exec "$DAEMON" --quiet
}

okfail() {
	if [ "$1" = 0 ]; then
		ok
	else
		fail
	fi
}

start() {
	# Check if the service is already running?
	if [ -f /var/lock/subsys/$NAME ]; then
		msg_already_running "$DESC"
		return
	fi

	msg_starting "$DESC"
	do_start
	RETVAL=$?
	okfail $RETVAL
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/$NAME
}

stop() {
	if [ ! -f /var/lock/subsys/$NAME ]; then
		msg_not_running "$DESC"
		return
	fi

	# Stop daemons.
	msg_stopping "$DESC"
	do_stop
	okfail $?
	rm -f /var/lock/subsys/$NAME
}

condrestart() {
	if [ ! -f /var/lock/subsys/$NAME ]; then
		msg_not_running "$DESC"
		RETVAL=$1
		return
	fi

	stop
	start
}

# run gitlab-runner register with proper uid/gid
register() {
	runuser -u "$USER" -g "$GROUP" gitlab-runner "$@"
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  register)
	register "$@"
	;;
  status)
	status --pidfile $PIDFILE $NAME
	RETVAL=$?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|register|status}"
	exit 3
esac

exit $RETVAL
