# Contributor: Carlo Landmeter <clandmeter@gmail.com>
# Maintainer: Jakub Jirutka <jakub@jirutka.cz>
pkgname=lua-lpeg
_pkgname=lpeg
pkgver=1.0.1
pkgrel=3
pkgdesc="Pattern-matching library for Lua"
url="http://www.inf.puc-rio.br/~roberto/lpeg"
arch="all"
license="MIT"
depends=""
makedepends=""
subpackages="$pkgname-dev"
source="http://www.inf.puc-rio.br/~roberto/lpeg/$_pkgname-$pkgver.tar.gz
	test-fix-setlocale.patch
	build-static-lib.patch"
builddir="$srcdir/$_pkgname-$pkgver"

# luajit is not available for selected arches
case "$CARCH" in
	s390x) _luajit="";;
	*) checkdepends="luajit" _luajit="jit";;
esac

_luaversions="5.1 5.2 5.3"
for _v in $_luaversions; do
	makedepends="$makedepends lua$_v-dev"
	subpackages="$subpackages lua$_v-$_pkgname:_package"
done

prepare() {
	default_prepare || return 1

	cd "$builddir"

	sed -i -e 's/^CFLAGS =/CFLAGS +=/' \
		-e 's/^COPT =/# COPT =/' \
		makefile || return 1

	local lver; for lver in $_luaversions; do
		cp -r "$builddir" "$builddir-$lver" || return 1
	done
}

build() {
	local lver; for lver in $_luaversions; do
		msg "Building for Lua $lver..."
		make -C "$builddir-$lver" LUADIR=/usr/include/lua$lver || return 1
	done
}

check() {
	local lver; for lver in $_luaversions $_luajit; do
		msg "Testing on lua$lver"

		cd "$builddir-${lver/jit/5.1}"
		lua$lver test.lua
	done
}

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

dev() {
	default_dev
	mkdir -p "$subpkgdir"

	local lver; for lver in $_luaversions; do
		install -Dm644 "$builddir-$lver"/lpeg.a \
			"$subpkgdir"/usr/lib/lua/$lver/lpeg.a || return 1
	done
}

_package() {
	local lver="${subpkgname:3:3}"
	pkgdesc="Pattern-matching library for Lua $lver"
	depends="lua$lver"
	install_if="lua$lver $pkgname=$pkgver-r$pkgrel"
	local rockdir="$subpkgdir/usr/lib/luarocks/rocks-$lver/$_pkgname/$pkgver-1"

	cd "$builddir-$lver"

	install -Dm755 lpeg.so \
		"$subpkgdir"/usr/lib/lua/$lver/lpeg.so || return 1
	install -Dm644 re.lua \
		"$subpkgdir"/usr/share/lua/$lver/re.lua || return 1

	mkdir -p "$rockdir"
	echo 'rock_manifest = {}' > "$rockdir"/rock_manifest
}

sha512sums="7b43fbee7eff443000986684bc56bba6d2796a31cf860740746c70e155bdea1b62a46b93f97e2747e3ef0f63e965148778ac2985d0f2d83e1e37ec4ebbabf4aa  lpeg-1.0.1.tar.gz
49ce012e6c2f6e07b3aae4f52630f3b4aa43f936f76dbfb2b8e33208fb05aec54e2e6c815215d606ee0dfc860b07917a042c77cdc0ea5b6b14a8028fa0e724f8  test-fix-setlocale.patch
3022a101639822f6d5ea38578a9efd29e22dba7433c770d0ebf6e7a35053ead26dae10a737a804061ea32daed8770812d9f9ca444acc1b0ea7329280223ae1fb  build-static-lib.patch"
