#!/bin/bash

#This is based on https://github.com/Alexpux/MINGW-packages/blob/master/mingw-w64-cyrus-sasl/PKGBUILD @ ccdb9fef07f2032affc628cdb8fa1a56f32ae667

set -x
set -u
set -e

PKGNAME=cyrus-sasl-2.1.26_daa1

BUILDSCRIPT=$(readlink -f $0)
BASEDIR=$(dirname $BUILDSCRIPT)
BUILDDIR=$BASEDIR/$PKGNAME
TARGETDIR=$BUILDDIR/target/$PKGNAME

rm -rf $BUILDDIR
mkdir $BUILDDIR

cd $BUILDDIR
tar -xf $BASEDIR/cyrus-sasl-2.1.26.tar.gz
cd cyrus-sasl-2.1.26

PATCHES="
	$BASEDIR/01-no-undefined.patch
	$BASEDIR/08-cyrus-sasl-2.1.26-size_t.patch
	$BASEDIR/12-MinGW-w64-uses-ws2_32-not-socket.patch
	$BASEDIR/13-MSYS2-Use-cp-f-instead-of-ln-s.patch
	$BASEDIR/16-MinGW-w64-define-WIN32_LEAN_AND_MEAN-avoiding-handle_t-redef.patch
	$BASEDIR/18-MinGW-w64-use-windlopen.c-not-dlopen.c.patch
	$BASEDIR/no_unistd_include.patch
	$BASEDIR/only_lib_subdirs.patch
	"

for PATCH in $PATCHES; do
	patch -p1 -i $PATCH || exit 1
done

sed 's/AM_CONFIG_HEADER/AC_CONFIG_HEADERS/' -i configure.in
rm -f config/config.guess config/config.sub
rm -f config/ltconfig config/ltmain.sh config/libtool.m4
rm -fr autom4te.cache
libtoolize -c
aclocal -I config -I cmulocal
automake -a -c
autoheader
autoconf

./configure --prefix= --without-saslauthd --without-authdaemond --without-pam --without-des --enable-shared --disable-static --without-staticsasl

make

mkdir -p $TARGETDIR
make DESTDIR=$TARGETDIR install

mkdir $TARGETDIR/src
cp $BUILDSCRIPT $PATCHES $TARGETDIR/src

(cd $TARGETDIR/..; tar czf $BUILDDIR/$PKGNAME.tar.gz $PKGNAME)
#gpg -ab $BUILDDIR/$PKGNAME.tar.gz
#gpg --verify $BUILDDIR/$PKGNAME.tar.gz.asc

