# Contributor: Łukasz Jendrysik <scadu@yandex.com>
# Maintainer: Natanael Copa <ncopa@alpinelinux.org>
_luaversions="5.1 5.2 5.3"
_drivers="mysql postgres sqlite3 odbc"

pkgname=lua-sql
_pkgname=luasql
pkgver=2.3.5
pkgrel=2
pkgdesc="Lua SQL drivers"
url="http://keplerproject.github.io/luasql/doc/us/"
arch="all"
license="MIT"
makedepends="mariadb-connector-c-dev postgresql-dev sqlite-dev unixodbc-dev"
subpackages=""
for _v in $_luaversions; do
	makedepends="$makedepends lua$_v-dev"
	for _d in $_drivers; do
		subpackages="$subpackages lua$_v-sql-$_d:_subpackage"
	done
done
for _d in $_drivers; do
	subpackages="$subpackages lua-sql-$_d:_meta_subpackage"
done

source="$_pkgname-$pkgver.tar.gz::https://github.com/keplerproject/$_pkgname/archive/v$pkgver.tar.gz
	luasql-mariadb.patch"
builddir="$srcdir/$_pkgname-$pkgver"

prepare() {
	default_prepare || return 1

	cd "$builddir"

	# The config has DRIVER_INCS but it seems like its not respected
	# so we just fix the .c file.
	sed -i 's:^\#include "mysql.h":\#include <mysql/mysql.h>:' \
		src/ls_mysql.c || return 1

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

build() {
	local cflags lver

	for lver in $_luaversions; do
		cflags="$CFLAGS $(pkg-config lua$lver --cflags) -fPIC"

		msg "Building for Lua $lver..."
		cd "$builddir-$lver"

		make CFLAGS="$cflags" DRIVER_LIBS="-lmysqlclient" \
			mysql || return 1

		make CFLAGS="$cflags" DRIVER_LIBS="$(pkg-config --libs libpq)" \
			postgres || return 1

		make CFLAGS="$cflags" DRIVER_LIBS="$(pkg-config --libs sqlite3)" \
			sqlite3 || return 1

		make CFLAGS="$cflags -DUNIXODBC" DRIVER_LIBS="-lodbc" \
			odbc || return 1
	done
}

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

_meta_subpackage() {
	local driver="${subpkgname##*-}"
	pkgdesc="$pkgdesc for $driver"

	mkdir -p "$subpkgdir"
}

_subpackage() {
	local lver="${subpkgname:3:3}"
	local driver="${subpkgname##*-}"
	pkgdesc="Lua $lver SQL driver for $driver"
	depends="lua$lver"
	install_if="lua-sql-$driver=$pkgver-r$pkgrel lua$lver"
	local rockdir="$subpkgdir/usr/lib/luarocks/rocks-$lver/$_pkgname/$pkgver-1"

	cd "$builddir-$lver"
	local install_cmod="$(pkg-config --variable INSTALL_CMOD lua$lver)"
	install -D src/$driver.so \
		"$subpkgdir"/$install_cmod/luasql/$driver.so

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

sha512sums="28e25998366a2517cdd37933f0f00e0bb4b06bd9b6731209361777d6b755d62d763168dc78177cab5dfeee667deea04ff775912fb148ed145d64cea5407df4e7  luasql-2.3.5.tar.gz
1c587dd5f8964079e8836a951eaf6f40fdd9482ee08c022e9f51af8b3630b01e404f836689ba35cb9a8e6eb25578fb3d444c89975192509822a62f9d514a6b0e  luasql-mariadb.patch"
