# 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=16.8.1
_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~=16.8
	gitlab-shell~=14.33
	graphicsmagick
	http-parser
	procps
	py-docutils
	python3
	redis>=2.8
	ruby3.2
	ruby3.2-bigdecimal
	ruby3.2-bundler
	ruby3.2-fiddle
	ruby3.2-io-console
	ruby3.2-irb
	ruby3.2-json
	ruby3.2-rake
	ruby3.2-rdoc
	ruby3.2-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
	ruby3.2-dev
	ruby3.2-grpc~=1.58
	ruby3.2-rugged
	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
	downgrade-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() {
	local sysgemdir=$(ruby -e 'puts Gem.default_dir')

	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

	# Some gems are broken, so we copy our fixed version
	# instead of installing it from RubyGems using Bundler.
	for i in grpc rugged; do
		mkdir -p vendor/gems/$i/src/ruby/lib/$i
		cp -r "$sysgemdir"/gems/$i-*/* vendor/gems/$i/
		cp "$sysgemdir"/specifications/$i-*.gemspec \
			vendor/gems/$i/$i.gemspec
		cp "$sysgemdir"/extensions/*/*/$i-*/$i/*.so \
			vendor/gems/$i/src/ruby/lib/$i/
	done
}

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

	# cp grpc lib
	cp vendor/gems/grpc/src/ruby/lib/grpc/grpc_c.so vendor/bundle/ruby/*/gems/grpc-*/src/ruby/lib/grpc/grpc_c.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="
9e36eec8209a64cbda254b851213a4ba97c629cbe1f8a008ead7a53e1bc308ac866e9c65a60bcad74f377155346c38b439a2282e4d74431d1642cb6d8b31ab5d  gitlab-foss-v16.8.1.tar.gz
daa496f3d9146f9dbddff62477bf49d5c7bd2f2a4cdbadc70ee51c8230f3ef01dc950ef157154b31c7e7bef0beecc5cbac50fbac65a79d6d9099b27bcba8b2ab  database-config.patch
55b0667d3969113ffd6860652ee8bdb9a534c25f413f33b2739e922c886988e7cea72c1c00c7eecf29fcff3682b1324156365605ffc6aae45d1e0ccddf96288b  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
ab9a09fca6126b18b76e61380990dc217f915162985880e90b905b3210a1fef229af3db1f1ca180177d3cba91ab5fe33798ac685055abf0adc44a1b630f71b39  downgrade-sys-filesystem-depend.patch
"