#!/sbin/runscript

name="GitLab"
description="GitLab @SLOT@ on Unicorns"

: ${gitlab_user:=@USER@}
: ${gitlab_group:=@GROUP@}
: ${gitlab_home:="@GITLAB_HOME@"}

: ${server_pidfile:="/run/gitlab/unicorn.pid"}
: ${rails_env:=production}

: ${resque_pidfile:="/run/gitlab/resque_worker.pid"}
: ${resque_log:="/var/log/gitlab-4.0/resque.log"}
: ${resque_queue:=@RESQUE_QUEUE@}

server_command="/usr/bin/bundle"
server_command_args="exec unicorn_rails -c ${gitlab_home}/config/unicorn.rb -E ${rails_env} -D"
resque_command="/usr/bin/bundle"
resque_command_args="exec rake environment resque:work QUEUE=${resque_queue} RAILS_ENV=${rails_env}"

if [ ${rails_env} = development ]; then
	resque_command_args+=" VVERBOSE=1"
fi

depend() {
	provide gitlab
	need redis
	use net
}

start() {
	ebegin "Starting GitLab @SLOT@ Unicorn servers"

	checkpath -d -o "${gitlab_user}:${gitlab_group}" -m750 "$(dirname "${server_pidfile}")"
	checkpath -d -o "${gitlab_user}:${gitlab_group}" -m750 "$(dirname "${resque_pidfile}")"

	start-stop-daemon --start \
		--chdir "${gitlab_home}" \
		--user="${gitlab_user}:${gitlab_group}" \
		--pidfile="${server_pidfile}" \
		--exec ${server_command} -- ${server_command_args}
	eend $?

	ebegin "Starting GitLab @SLOT@ Resque worker"

	start-stop-daemon --start \
		--background --quiet \
		--chdir "${gitlab_home}" \
		--user="${gitlab_user}:${gitlab_group}" \
		--make-pidfile --pidfile=${resque_pidfile} \
		--stdout "${resque_log}" --stderr "${resque_log}" \
		--exec ${resque_command} -- ${resque_command_args}
	eend $?
}

stop() {
	ebegin "Stopping GitLab @SLOT@ Resque worker"
	start-stop-daemon --stop \
		--pidfile=${resque_pidfile} \
		--exec ${resque_command}
	eend $?

	ebegin "Stopping GitLab @SLOT@ Unicorn servers"
	start-stop-daemon --stop \
		--pidfile=${server_pidfile} \
		--exec ${server_command} -- ${server_command_args}
	eend $?
}