# Maintainer: Antoine Martin (ayakael) <dev@ayakael.net>
# Contributor: Jakub Jirutka <jakub@jirutka.cz>
# Contributor: Antoine Martin (ayakael) <dev@ayakael.net>
pkgname=gitlab-foss
_pkgname=${pkgname%-foss}
pkgver=17.0.4
_gittag=v$pkgver
pkgrel=0
pkgdesc="A version control for your server"
url="https://gitlab.com/gitlab-org/gitlab-foss"
arch="x86_64 aarch64"
license="MIT"
# ruby-irb is needed only for Rails console (gitlab-rails console)
depends="
	$pkgname-assets=$pkgver-r$pkgrel
	ca-certificates
	cmd:dpkg-deb
	exiftool
	git>=2.42.0
	gitaly~=17.0
	gitlab-shell>=14.35
	graphicsmagick
	http-parser
	procps
	py-docutils
	python3
	redis>=2.8
	ruby
	ruby-bigdecimal
	ruby-bundler
	ruby-fiddle
	ruby-io-console
	ruby-irb
	ruby-json
	ruby-rake
	ruby-rdoc
	ruby-webrick
	shared-mime-info
	tzdata
	"
makedepends="
	cargo
	clang-dev
	cmd:chrpath
	cmake
	file-dev
	go
	gpgme-dev
	icu-dev
	libffi-dev
	libgcrypt-dev
	libpq-dev
	libxml2-dev
	libxslt-dev
	linux-headers
	llvm
	nodejs
	openssl-dev
	protobuf-dev
	re2-dev
	ruby-dev
	rust
	yarn>=1.2.0
	"
pkgusers="git"
pkggroups="git www-data"
install="$pkgname.pre-install $pkgname.post-install $pkgname.post-upgrade"
subpackages="$pkgname-assets::noarch $pkgname-openrc"
source="https://gitlab.com/gitlab-org/gitlab-foss/-/archive/$_gittag/gitlab-foss-$_gittag.tar.gz
	database-config.patch
	$_pkgname.initd
	$_pkgname.mailroom.initd
	$_pkgname.rails.initd
	$_pkgname.sidekiq.initd
	$_pkgname.workhorse.initd
	$_pkgname.confd
	$_pkgname.logrotate
	bin-wrapper.in
	upgrade-sys-filesystem-depend.patch
	"
builddir="$srcdir/gitlab-foss-$_gittag"

_prefix="usr/lib/bundles/$_pkgname"

export BUNDLE_DEPLOYMENT=true
export BUNDLE_FORCE_RUBY_PLATFORM=true
export BUNDLE_FROZEN=true
# Should be tied to $JOBS, but rust native code fails to build
export BUNDLE_JOBS=1

prepare() {
	default_prepare

	# The default log level is very chatty.
	sed -i 's/^\(\s*config.log_level\s*=\).*$/\1 :warn/' \
		config/environments/production.rb

	# This is not needed, the secret_token is generated by the
	# gitlab-shell package. It also makes problems in the build phase.
	rm config/initializers/gitlab_shell_secret_token.rb

	# Remove all locale files except en.
	find locale -type d -mindepth 1 ! -name en -exec rm -rf {} +

	# Allow use of any bundler
	sed -i -e '/BUNDLED/,+1d' Gemfile.lock
}

build() {
	local bundle_without='exclude development kerberos mysql test'

	cd "$builddir"/workhorse

	make

	cd "$builddir"

	msg "Installing Ruby gems..."
	bundle config --local without "$bundle_without"
	bundle config --local build.ffi --enable-system-libffi
	bundle config --local build.gpgme --use-system-libraries
	bundle config --local build.re2 --enable-system-libraries
	bundle config --local build.nokogiri --use-system-libraries \
		--with-xml2-include=/usr/include/libxml2 \
		--with-xslt-include=/usr/include/libxslt
	bundle config --local build.ruby-magic --enable-system-libraries
	bundle config --local build.google-protobuf '-- --with-cflags=-D__va_copy=va_copy'
	bundle config --local path "vendor/bundle"

	bundle install --no-cache

	# Replace bundled CA bundle with symlink.
	(
		cd vendor/bundle/ruby/*/gems/aws-sdk-core-*/
		rm ca-bundle.crt
		ln -s /etc/ssl/certs/ca-certificates.crt ca-bundle.crt
	)

	# Remove faulty RPATH.
	chrpath -d vendor/bundle/ruby/*/extensions/*/*/ruby-magic-*/magic/magic.so

	# Patch installed gem gitlab-markup to use python3.
	# Option "-S" causes that Python cannot find docutils module.
	sed -i 's/python2 -S/python3/g' \
		vendor/bundle/ruby/*/gems/gitlab-markup-*/lib/github/markups.rb

	# Remove non-sense require of code for tests from top-level module
	# (we're gonna delete tests from the package).
	sed -i '/require .carrierwave\/test\/matchers./d' \
		vendor/bundle/ruby/*/gems/carrierwave-*/lib/carrierwave.rb

	msg "Installing npm modules..."
	yarn install --production --frozen-lockfile

	# Since we have moved assets gems into a group, they are not implicitly
	# loaded by default. This will be reverted after compiling assets.
	sed -i.bak '/Bundler.require(\*Rails.groups/s/)/, :assets)/' \
		config/application.rb

	# assets:precompile and gettext:compile bootstraps the app,
	# so they needs configs.
	cp config/gitlab.yml.example config/gitlab.yml
	cp config/database.yml.postgresql config/database.yml
	cp config/secrets.yml.example config/secrets.yml

	# The configured path is not readable for the user building
	# the package, so we must remove it; GitLab will use the default path.
	sed -i '/^\s*secret_file:.*/d' config/gitlab.yml

	(
		export NODE_ENV=production
		export RAILS_ENV=production
		export SKIP_STORAGE_VALIDATION=true
		export USE_DB=false
		export NO_SOURCEMAPS=true
		export NODE_OPTIONS="--max_old_space_size=3584"

		msg "Compiling GetText PO files..."
		bundle exec rake gettext:compile

		msg "Compiling assets (this will take few minutes)..."
		bundle exec rake gitlab:assets:compile
	)

	# Revert changes.
	mv config/application.rb.bak config/application.rb

	msg "Cleaning assets gems..."
	bundle config --local without 'exclude development kerberos mysql test assets'
	bundle clean

	# Create executables in bin/*.
	# See also https://github.com/bundler/bundler/issues/6149.
	bundle binstubs --force bundler gitlab-mail_room puma sidekiq

	# Cleanup
	rm config/database.yml config/gitlab.yml config/secrets.yml
}

package() {
	local destdir="$pkgdir/$_prefix"
	local datadir="$pkgdir/var/lib/gitlab"
	local file dest

	install -d -m755 "$destdir" "$destdir"/bin

	install -d -m755 -o git -g git \
		"$datadir" \
		"$pkgdir"/etc/gitlab \
		"$pkgdir"/var/log/gitlab \
		"$datadir"/pages

	install -d -m700 -o git -g git \
		"$datadir"/artifacts \
		"$datadir"/builds \
		"$datadir"/ci_secure_files \
		"$datadir"/dependency_proxy \
		"$datadir"/encrypted_settings \
		"$datadir"/external-diffs \
		"$datadir"/lfs-objects \
		"$datadir"/packages \
		"$datadir"/pages \
		"$datadir"/terraform_state \
		"$datadir"/uploads \
		"$pkgdir"/var/tmp/gitlab \
		"$pkgdir"/var/tmp/gitlab/downloads \
		"$pkgdir"/var/tmp/gitlab/backups

	install -d -m0750 -o git -g www-data \
		"$datadir"/pages

	install -d -m02770 -o git -g git \
		"$datadir"/repositories

	# Install application files.
	# Note: *VERSION files and doc directory are required (Help in GitLab
	# menu refers to the doc directory).
	cp -rl .bundle config.ru Gemfile* INSTALLATION_TYPE Rakefile ./*VERSION \
		app data db doc fixtures config lib locale metrics_server public sidekiq_cluster vendor gems \
		"$destdir"/

	install -m755 -t "$destdir"/bin/ \
		bin/bundle \
		bin/mail_room \
		bin/metrics-server \
		bin/rails \
		bin/rake \
		bin/sidekiq \
		bin/sidekiq-cluster \
		bin/sidekiqmon \
		bin/puma

	cd "$destdir"

	# Not needed in runtime since we have already compiled all assets.
	rm -r app/assets
	rm -r vendor/assets
	find public/assets -name '*.vue' -delete
	find public/assets -type d -exec rmdir --ignore-fail-on-non-empty '{}' \;
	# These load gems in the assets group.
	rm config/initializers/sprockets.rb

	# Remove more stuff not neeeded in production.
	rm -r lib/support
	rm -r db/fixtures/development
	find lib/tasks -maxdepth 1 -type f ! -name cache.rake ! -name setup.rake -delete
	find lib/tasks/gitlab \( -name 'generate_docs.*' \
	                      -o -name 'shell.*' \
	                      -o -name 'test.*' \) -delete


	cd "$destdir"/vendor/bundle/ruby/*/

	# Remove tests, documentations and other useless files.
	find gems/ \( -name 'doc' \
	           -o -name 'spec' \
	           -o -name 'test' \) \
		-type d -maxdepth 2 -exec rm -fr "{}" +
	find gems/ \( -name 'README*' \
	           -o -name 'CHANGELOG*' \
	           -o -name 'CONTRIBUT*' \
	           -o -name '*LICENSE*' \
	           -o -name 'Rakefile' \
	           -o -name '.*' \) \
		-type f -delete

	# Remove bundled libgit2 sources.
	rm -r gems/rugged-*/vendor/libgit2

	# Remove assets, they are already compiled.
	rm -r gems/tanuki_emoji-*/app/assets

	# Remove build logs and cache.
	rm -rf build_info/ cache/
	find extensions/ \( -name gem_make.out -o -name mkmf.log \) -delete


	cd "$destdir"

	# Install and symlink config files.
	for file in cable.yml.example \
			database.yml.postgresql \
			gitlab.yml.example \
			puma.rb.example \
			resque.yml.example \
			sidekiq.yml.example \
			initializers/smtp_settings.rb.sample
	do
		dest="$(basename "${file%.*}")"
		install -m640 -g git -D config/$file "$pkgdir"/etc/gitlab/$dest
		ln -sf /etc/gitlab/$dest "$pkgdir"/$_prefix/config/${file%.*}
	done

	# This file will be generated by the post-install script, just prepare symlink.
	ln -sf /etc/gitlab/secrets.yml config/secrets.yml
	# These shouldn't be necessary, they are all configurable, but OmniBus
	# creates them too, so just to be sure...
	ln -sf /etc/gitlab/gitlab_kas_secret .gitlab_kas_secret
	ln -sf /etc/gitlab/gitlab_pages_secret .gitlab_pages_secret
	ln -sf /etc/gitlab/gitlab_shell_secret .gitlab_shell_secret
	ln -sf /etc/gitlab/gitlab_workhorse_secret .gitlab_workhorse_secret

	# Some paths are hard-coded in GitLab, so we must make symlinks. :(
	ln -sf /var/lib/gitlab/uploads public/uploads
	ln -sf /var/log/gitlab log
	ln -sf /var/tmp/gitlab tmp

	cat > "$datadir"/.profile <<-EOF
		export RAILS_ENV=production
		export NODE_ENV=production
		export EXECJS_RUNTIME=Disabled
	EOF

	# Install wrapper scripts to /usr/bin.
	local name; for name in rake rails; do
		sed "s/__COMMAND__/$name/g" "$srcdir"/bin-wrapper.in \
			> "$builddir"/gitlab-$name
		install -m755 -D "$builddir"/gitlab-$name "$pkgdir"/usr/bin/gitlab-$name
	done


	cd "$builddir"/workhorse

	# Install workhorse.
	make install DESTDIR="$pkgdir" PREFIX=/usr
	install -m644 config.toml.example "$pkgdir"/etc/gitlab/workhorse.toml


	for file in $_pkgname $_pkgname.rails $_pkgname.sidekiq $_pkgname.mailroom $_pkgname.workhorse; do
		install -m755 -D "$srcdir"/$file.initd "$pkgdir"/etc/init.d/$file
	done

	install -m644 -D "$srcdir"/$_pkgname.confd \
		"$pkgdir"/etc/conf.d/$_pkgname

	install -m644 -D "$srcdir"/$_pkgname.logrotate \
		"$pkgdir"/etc/logrotate.d/$_pkgname
}

assets() {
	depends=""

	amove $_prefix/public/assets
}

sha512sums="
e09cfbbe4237f42bd8509c551031fd3526b75762beae7dac5164ecc4056ae07890a3ddb8500f1573f0ca9d697150654d1fcab3b3d0a3b93e5382addcee298c5b  gitlab-foss-v17.0.4.tar.gz
daa496f3d9146f9dbddff62477bf49d5c7bd2f2a4cdbadc70ee51c8230f3ef01dc950ef157154b31c7e7bef0beecc5cbac50fbac65a79d6d9099b27bcba8b2ab  database-config.patch
80d9bf2d064c1d4310566e087e14220e075430c46d9a6c4641c1141fbdc05381ae14a3ae7dfcb7dcb75dbf7af17a136f81764c7a4d109f248a81033782dce23b  gitlab.initd
1f451b67a5d5e58650b0fe862a2b65cfb8bff5502b37d94ae90619c1ff9affbecf24428303a2849bebce5f94bef37078f0e5710e344bbab616134e910938384a  gitlab.mailroom.initd
b6a6d9ba20557e61efa24f2d5a489873fefbb981f7d4465794a857b2971263c08ec29cc001c372522cdc0d48245e59751307c9f44f6ef4d87bf2e3ec5c23fb1c  gitlab.rails.initd
cb4ec100f0ea7ffcbb37aead8423e636629e2f4848b2974a7b2468e96cb1081ca732ac336417b08dd943afb961df888c73af1334dcbe054dfd361e74f492fd86  gitlab.sidekiq.initd
85c4e257a030832bd70ad1e257ae7cb568b31e01201fc845abac02d00f02492ca694be1fa2bf743dd8c8623e6a79d36adee3f4de02040134c11158a6001c064b  gitlab.workhorse.initd
4dc00b16462f30591297fcb535fc364185d3ed76e9956597f0423a8dfd8a9a351f6ac29d9f0c73052c11324fba4768eb89a21c6bef4da99f15baaea8c9ab8407  gitlab.confd
57f258246925fbef0780caebdf005983c72fe3db1ab3242a1e00137bd322f5ec6c0fd958db7178b8fc22103d071f550d6f71f08422bcd9e859d2a734b2ecef00  gitlab.logrotate
a944c3886388ba1574bf8c96b6de4d9f24ef4a83f553c31a224e17a3b01f2a5c65b60c59b7ed7ca4b25670c60ea8dd41b96a8a623d909d2bb09bdf2520ed7f23  bin-wrapper.in
0eaa7de9a906ddb0fe84b7afbaec893a134bbbdb9e71da75cf4095ef40404643e51447aee88d3cad6e565bc709b34ffd8901cc93061e4a2a410838aed42d3644  upgrade-sys-filesystem-depend.patch
"
