#!/bin/sh
#
# Copyright (c) 2019-2021 David Demelier <markand@malikania.fr>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

PKGNAME=pcre2
PKGVERSION=10.39
PKGREVISION=1
PKGLICENSE="BSD-3-Clause"
PKGSUMMARY="perl 5 regular expression library (2nd version)"
PKGWWW="http://pcre.org"
PKGDOWNLOAD="https://github.com/PhilipHazel/pcre2/archive/refs/tags/$PKGNAME-$PKGVERSION.tar.gz"
PKGOPTIONS="BZIP2 COMPLETION ZLIB"

: ${CHOST:=$(uname -m)-linux-musl}
: ${CBUILD:=$(uname -m)-linux-musl}
: ${CC:=clang}
: ${CFLAGS:=-O2}
: ${LDFLAGS:=}
: ${LIBS:=}
: ${BZIP2:=yes}
: ${COMPLETION:=readline}       # Select: readline|yes, libedit, no
: ${ZLIB:=yes}

if [ "$BZIP2" = "yes" ]; then
	PKGDEPENDS="bzip2 $PKGDEPENDS"
	with_bzip2="-DPCRE2_SUPPORT_LIBBZ2=On"
else
	with_bzip2="-DPCRE2_SUPPORT_LIBBZ2=Offn"
fi

case $COMPLETION in
yes|readline)
	PKGDEPENDS="readline $PKGDEPENDS"
	with_completion="-DPCRE2_SUPPORT_LIBEDIT=Off -DPCRE2_SUPPORT_LIBREADLINE=On"
	;;
libedit)
	PKGDEPENDS="libedit $PKGDEPENDS"
	with_completion="-DPCRE2_SUPPORT_LIBEDIT=On -DPCRE2_SUPPORT_LIBREADLINE=Off"
	;;
no)
	with_completion="-DPCRE2_SUPPORT_LIBEDIT=Off -DPCRE2_SUPPORT_LIBREADLINE=Off"
	;;
esac

if [ "$ZLIB" = "yes" ]; then
	PKGDEPENDS="zlib $PKGDEPENDS"
	with_zlib="-DPCRE2_SUPPORT_LIBZ=On"
else
	with_zlib="-DPCRE2_SUPPORT_LIBZ=Off"
fi

build()
{
	rm -rf $PKGNAME-$PKGNAME-$PKGVERSION
	tar -xvf $PKGNAME-$PKGVERSION.tar.gz
	cd $PKGNAME-$PKGNAME-$PKGVERSION

	# -DPCRE2_BUILD_PCRE2_(16|32): some packages require this (e.g. qtbase)
	cmake -S . -B build \
		-DBUILD_SHARED_LIBS=On \
		-DCMAKE_BUILD_TYPE=Release \
		-DCMAKE_C_COMPILER="$CC" \
		-DCMAKE_C_FLAGS="$CFLAGS" \
		-DCMAKE_INSTALL_PREFIX= \
		-DPCRE2_BUILD_PCRE2_16=On \
		-DPCRE2_BUILD_PCRE2_32=On \
		$with_bzip2 \
		$with_completion \
		$with_zlib
	cmake --build build
	DESTDIR=$DESTDIR cmake --build build --target install

	cd ..
	rm -rf $PKGNAME-$PKGNAME-$PKGVERSION
}
