#!/bin/sh
#
# gitlab-workhorse GitLab Workhorse
#
# chkconfig:	345 82 18
# description: Runs GitLab Workhorse
# processname: gitlab-workhorse

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

# Get network config
. /etc/sysconfig/network

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down "GitLab Workhorse"
		exit 1
	fi
else
	exit 0
fi

### Environment variables
RAILS_ENV="production"

# The username and path to the gitlab source
USER=git
APP_PATH=/usr/lib/gitlab

# The PID and LOCK files
pidfile=/var/run/gitlab/gitlab-workhorse.pid
lockfile=/var/lock/subsys/gitlab-workhorse

# Get service config - may override defaults
[ -f /etc/sysconfig/gitlab-workhorse ] && . /etc/sysconfig/gitlab-workhorse

start() {
	# Check if the service is already running?
	if [ -f $lockfile ]; then
		msg_already_running "GitLab Workhorse"
		return
	fi

	msg_starting "GitLab Workhorse"
	# initlog would cause fd1 and fd2 to be pipe
	# those won't exist when workhorse tries to write to stdout causing it to abort with SIGPIPE
	# http://lists.pld-linux.org/mailman/pipermail/pld-devel-en/2016-September/025111.html
	RC_LOGGING=no
	daemon --pidfile $pidfile --user $USER --makepid --chdir "$APP_PATH" --redirfds --fork \
		/usr/sbin/gitlab-workhorse $OPTIONS $LISTEN_OPTIONS
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch $lockfile
}

stop() {
	if [ ! -f $lockfile ]; then
		msg_not_running "GitLab Workhorse"
		return
	fi

	# Stop daemons.
	msg_stopping "GitLab Workhorse"
	killproc --pidfile $pidfile gitlab-workhorse
	RETVAL=$?
	rm -f $lockfile
}

condrestart() {
	if [ ! -f $lockfile ]; then
		msg_not_running "GitLab Workhorse"
		RETVAL=$1
		return
	fi

	stop
	start
}

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
	;;
  status)
	status --pidfile $pidfile gitlab-workhorse
	RETVAL=$?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|status}"
	exit 3
esac

exit $RETVAL
