#!/bin/sh -e
# Create the secrets of GitLab once, before starting any consumer.
# The existing files are never changed.

umask 027

exec 9>/run/lock/gitlab-secrets.lock
/usr/bin/flock -x 9

# The Rails secrets: the same keys as config/initializers/2_secret_token.rb creates.
if [ ! -e /etc/gitlab/secrets.yml ] ; then
	ruby -rsecurerandom -ropenssl -ryaml -e '
		secrets = {
		  "secret_key_base" => SecureRandom.hex(64),
		  "otp_key_base" => SecureRandom.hex(64),
		  "db_key_base" => SecureRandom.hex(64),
		  "openid_connect_signing_key" => OpenSSL::PKey::RSA.new(2048).to_pem,
		  "active_record_encryption_primary_key" => [SecureRandom.alphanumeric(32)],
		  "active_record_encryption_deterministic_key" => [SecureRandom.alphanumeric(32)],
		  "active_record_encryption_key_derivation_salt" => SecureRandom.alphanumeric(32)
		}
		File.write(ARGV[0], YAML.dump("production" => secrets))' /etc/gitlab/secrets.yml.new
	install -m 0640 -o root -g git /etc/gitlab/secrets.yml.new /etc/gitlab/secrets.yml
	rm -f /etc/gitlab/secrets.yml.new
fi

# The secret of the internal API shared with gitlab-shell and gitaly.
if [ ! -e /etc/gitlab-shell/.gitlab_shell_secret ] ; then
	# the directory of gitlab-shell (it is installed first, Requires)
	[ -d /etc/gitlab-shell ] || install -d -m 0755 /etc/gitlab-shell
	ruby -rsecurerandom -e 'puts SecureRandom.hex(16)' > /etc/gitlab-shell/.gitlab_shell_secret.new
	install -m 0640 -o root -g git /etc/gitlab-shell/.gitlab_shell_secret.new /etc/gitlab-shell/.gitlab_shell_secret
	rm -f /etc/gitlab-shell/.gitlab_shell_secret.new
fi

# The secrets shared with gitlab-workhorse, gitlab-pages and the kubernetes
# agent server (32 random bytes in base64): Rails writes the KAS one on
# the boot if it is missing.
for name in workhorse pages kas ; do
	f=/etc/gitlab/.gitlab_${name}_secret
	[ ! -e "$f" ] || continue
	ruby -rsecurerandom -e 'puts [SecureRandom.random_bytes(32)].pack("m0")' > "$f.new"
	install -m 0640 -o root -g git "$f.new" "$f"
	rm -f "$f.new"
done
