# Contributor: Carlo Landmeter <clandmeter@alpinelinux.org>
# Maintainer: Jakub Jirutka <jakub@jirutka.cz>
pkgname=luarocks
pkgver=3.11.0
pkgrel=0
pkgdesc="Deployment and management system for Lua modules"
url="https://luarocks.org/"
arch="noarch"
license="MIT"
depends="curl"
source="https://luarocks.org/releases/$pkgname-$pkgver.tar.gz
	prefer-curl-to-wget.patch
	config.lua
	"

_lua_versions="5.1 5.2 5.3 5.4"
for _v in $_lua_versions; do
	makedepends="$makedepends lua$_v-dev"
	subpackages="$subpackages $pkgname${_v}:_subpackage"
	triggers="$triggers $pkgname$_v.trigger=/usr/lib/luarocks/rocks-$_v:/usr/lib/luarocks/rocks-common"
done

prepare() {
	default_prepare

	# Create builddir for each Lua version.
	local lver; for lver in $_lua_versions; do
		cp -r "$builddir" "$builddir-$lver"
	done
}

build() {
	local lver; for lver in $_lua_versions; do
		msg "Building for Lua $lver..."
		cd "$builddir-$lver"

		./configure \
			--prefix=/usr \
			--sysconfdir=/etc \
			--rocks-tree=/usr/local \
			--lua-version="$lver" \
			--with-lua-include="$(pkg-config --variable=includedir lua$lver)" \
			--with-lua-lib="$(pkg-config --variable=libdir lua$lver)"
		make
	done
}

package() {
	mkdir -p "$pkgdir"
}

_subpackage() {
	local lver="${subpkgname#$pkgname}"
	pkgdesc="Deployment and management system for Lua $lver modules"
	install_if="lua$lver $pkgname=$pkgver-r$pkgrel"
	depends="$depends lua$lver"

	cd "$builddir-$lver"

	make install DESTDIR="$subpkgdir"

	# Move default scripts which conflict per Lua version.
	mv "$subpkgdir"/usr/bin/luarocks "$subpkgdir"/usr/bin/luarocks-"$lver"
	mv "$subpkgdir"/usr/bin/luarocks-admin "$subpkgdir"/usr/bin/luarocks-admin-"$lver"

	# Set the correct Lua version.
	sed -i "s/env lua/env lua$lver/" \
		"$subpkgdir"/usr/bin/luarocks-$lver \
		"$subpkgdir"/usr/bin/luarocks-admin-$lver

	# Config based on:
	#   https://github.com/luarocks/luarocks/wiki/Integrating-distro-modules-with-LuaRocks
	install -D -m 644 "$srcdir"/config.lua "$subpkgdir"/etc/$pkgname/config-$lver.lua
}

sha512sums="
bec918e98209e5ff5c498c4454b8c8182ecfeb0786cb4cd241d59149f33560e981ff2db8d49785823ccf31643366de15b5f2599c6eef0951d17ba66436b79644  luarocks-3.11.0.tar.gz
e8ea793df118bd9b871d44706d9b51b95e0ae437dd4262df405c2ac45529f34cf88e06f1ba857abb4ce37b7df0e15777aba104c740709d2485d6579eadf3c032  prefer-curl-to-wget.patch
5845d5643c3eeb6d4af6d919a588c5253c91e6a0b278116b4cd855437fc48ac64970fd3ef758c135bc0536ddc1aaa16b01c50e33c864f59aeef1ccced0d01d82  config.lua
"
