#!/bin/sh
#
# Copyright (c) 2019 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=nss
PKGVERSION=3.47
_VER=$(echo $PKGVERSION | tr '.' '_')
PKGREVISION=1
PKGLICENSE="MPLv20"
PKGSUMMARY="Mozilla Network Security Services"
PKGWWW="https://wiki.mozilla.org/NSS"
PKGDOWNLOAD="https://ftp.mozilla.org/pub/security/nss/releases/NSS_${_VER}_RTM/src/$PKGNAME-$PKGVERSION.tar.gz"
PKGDEPENDS="nspr"

: ${CC:=clang}
: ${CFLAGS:=-O2}
: ${CXX:=clang++}
: ${CXXFLAGS:=-O2}

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

	make -C nss \
		BUILD_OPT=1 \
		CC="$CC" \
		CCC="$CXX" \
		CXX="$CXX" \
		NSPR_INCLUDE_DIR=/include/nspr \
		NSPR_LIB_DIR=/lib \
		NSS_DISABLE_GTESTS=1 \
		NSS_USE_SYSTEM_SQLITE=1 \
		USE_SYSTEM_ZLIB=1 \
		USE_64=1

	mkdir -p $DESTDIR/lib/pkgconfig
	mkdir -p $DESTDIR/bin
	mkdir -p $DESTDIR/include/nss

	# Copy only stuff as recommended per BLFS.
	cp -p dist/Linux*/lib/*.so $DESTDIR/lib
	cp -p dist/Linux*/lib/*.chk $DESTDIR/lib
	cp -p dist/Linux*/lib/libcrmf.a $DESTDIR/lib
	cp -p dist/Linux*/bin/*util $DESTDIR/bin
	cp -p dist/public/nss/*.h $DESTDIR/include/nss

	# Obtain version from header.
	major=$(awk '/^#define NSS_VMAJOR/ { print $3 }' nss/lib/nss/nss.h)
	minor=$(awk '/^#define NSS_VMINOR/ { print $3 }' nss/lib/nss/nss.h)
	patch=$(awk '/^#define NSS_VPATCH/ { print $3 }' nss/lib/nss/nss.h)

	sed nss/pkg/pkg-config/nss.pc.in \
		-e "s|%NSPR_VERSION%|$(pkgconf --modversion nspr)|" \
		-e "s|%NSS_VERSION%|$major.$minor.$patch|" \
		-e "s|%exec_prefix%||" \
		-e "s|%includedir%|/include/nss|" \
		-e "s|%libdir%|/lib|" \
		-e "s|%prefix%||" > $DESTDIR/lib/pkgconfig/nss.pc
	sed nss/pkg/pkg-config/nss-config.in \
		-e "s|@MOD_MAJOR_VERSION@|$major|" \
		-e "s|@MOD_MINOR_VERSION@|$minor|" \
		-e "s|@MOD_PATCH_VERSION@|$patch|" \
		-e "s|@prefix@||" > $DESTDIR/bin/nss-config
	chmod 0755 $DESTDIR/bin/nss-config

	cd -
	rm -rf $PKGNAME-$PKGVERSION
}
