#!/sbin/openrc-run

name="GitLab Rails"
description="GitLab application"

extra_started_commands="reload reopen"
description_reload="Reload configuration"
description_reopen="Reopen log files"

: ${gitlab_base:="/usr/lib/bundles/gitlab"}
: ${metrics_dir:="/dev/shm/gitlab"}

: ${action_cable_worker_pool_size:=4}
: ${gitlab_config:="/etc/gitlab/gitlab.yml"}
: ${puma_workers:=3}
: ${puma_listen_unix:="/run/gitlab/gitlab.socket"}
: ${puma_listen_tcp:="127.0.0.1:8080"}
: ${puma_stdout_file:="/var/log/gitlab/puma_stdout.log"}
: ${puma_stderr_file:="/var/log/gitlab/puma_stderr.log"}
: ${puma_config:="/etc/gitlab/puma.rb"}
: ${puma_metrics_dir:="$metrics_dir/puma"}

command="$gitlab_base/bin/puma"
command_args="
	--config $puma_config
	--workers $puma_workers
	--bind tcp://$puma_listen_tcp
	--bind unix://$puma_listen_unix
	--redirect-stdout $puma_stdout_file
	--redirect-stderr $puma_stderr_file
	--redirect-append
	--state /run/gitlab/puma.state
	"
command_background="yes"
command_user="git"
directory="$gitlab_base"

supervise_daemon_args="
	--env ACTION_CABLE_WORKER_POOL_SIZE=$action_cable_worker_pool_size
	--env RAILS_ENV=production
	--env NODE_ENV=production
	--env EXECJS_RUNTIME=Disabled
	--env GITLAB_BASE=$gitlab_base
	--env TZ=:/etc/localtime
	--env prometheus_multiproc_dir=$puma_metrics_dir
	${supervise_daemon_args:-}
	"
start_stop_daemon_args="
	--interpreted
	$supervise_daemon_args
	$start_stop_daemon_args
	"
pidfile="/run/gitlab/puma.pid"

required_files="$gitlab_config $puma_config"

depend() {
	need redis
	want sshd postgresql docker-registry
	use net
}

start_pre() {
	checkpath -d -m 755 -o $command_user -q "${pidfile%/*}" || return 1
	checkpath -d -m 700 -o $command_user -q "$(readlink -f "$gitlab_base"/tmp)" || return 1
	checkpath -d -m 700 -o $command_user -q "$metrics_dir" || return 1
	checkpath -d -m 700 -o $command_user --directory-truncate "$puma_metrics_dir" || return 1
	checkpath -f -m 644 -o $command_user "$puma_stdout_file" || return 1
	checkpath -f -m 644 -o $command_user "$puma_stderr_file" || return 1

	# Ruby requires sticky bit on TMP directory.
	checkpath -d -m 1777 /tmp

	local downloads_path="$(_parse_yaml "$gitlab_config" \
		production.gitlab.repository_downloads_path)"

	if [ -n "$downloads_path" ]; then
		checkpath -d -m 700 -o $command_user -q "$downloads_path"
	fi
}

reload() {
	ebegin "Reloading $name"

	if [ "$supervisor" ]; then
		$supervisor "$RC_SVCNAME" --signal USR2
	else
		start-stop-daemon --pidfile "$pidfile" --signal USR2
	fi
	eend $?
}

reopen() {
	ebegin "Telling $name to reopen log files"

	if [ "$supervisor" ]; then
		$supervisor "$RC_SVCNAME" --signal USR1
	else
		start-stop-daemon --pidfile "$pidfile" --signal USR1
	fi
	eend $?
}

_parse_yaml() {
	local file="$1"
	local key="$2"
	local default="${3:-}"
	local key_path="$(echo "[\"$key\"]" | sed 's/\./"]["/g')"

	ruby <<-EOF
	require "yaml"
	puts YAML.load_file("$file")$key_path rescue puts "$default"
	EOF
}
