#!/bin/bash

set -e

#PREFIX=i686-w64-mingw32
PREFIX=x86_64-w64-mingw32
POSTFIX=-win32
export CC=$PREFIX-gcc$POSTFIX
export CXX=$PREFIX-g++$POSTFIX
export CPP=$PREFIX-cpp$POSTFIX
export RANLIB=$PREFIX-ranlib
#export PATH="/usr/$PREFIX/bin:$PATH"

export INSTALLDIR="$PWD/$PREFIX"
export PKG_CONFIG_PATH=$INSTALLDIR/lib/pkgconfig:/usr/$PREFIX/lib/pkgconfig
export CPPFLAGS="-I$INSTALLDIR/include"
export LDFLAGS="-L$INSTALLDIR/lib"

# let mingw compiler be less verbose
export CFLAGS="-O2 -Wall -Wno-format"

if [ ! -d libunistring ]; then
  git clone https://git.savannah.gnu.org/git/libunistring.git
  cd libunistring
else
  cd libunistring
  git pull
fi
./autogen.sh
./configure --build=x86_64-pc-linux-gnu --host=$PREFIX --enable-static --enable-shared --prefix=$INSTALLDIR
make clean
make -j$(nproc)
make install
cd ..

if [ ! -d libidn2 ]; then
  git clone https://gitlab.com/libidn/libidn2.git
  cd libidn2
else
  cd libidn2
  git pull
fi
./bootstrap
./configure --build=x86_64-pc-linux-gnu --host=$PREFIX --enable-shared --disable-doc --disable-gcc-warnings --prefix=$INSTALLDIR
make clean
make -j$(nproc)
make install
cd ..

if [ ! -d nettle ]; then
  git clone https://git.lysator.liu.se/nettle/nettle.git
  cd nettle
else
  cd nettle
  git pull
fi
bash .bootstrap
./configure --build=x86_64-pc-linux-gnu --host=$PREFIX --enable-mini-gmp --enable-shared --disable-documentation --prefix=$INSTALLDIR
make clean
make -j$(nproc)
make install
cd ..

if [ ! -d gnutls ]; then
  git clone --depth=1 https://gitlab.com/gnutls/gnutls.git
  cd gnutls
else
  cd gnutls
  git pull
fi
#make bootstrap
make autoreconf && touch .submodule.stamp
./configure --build=x86_64-pc-linux-gnu --host=$PREFIX \
  --with-nettle-mini --enable-gcc-warnings --enable-shared --disable-static --with-included-libtasn1 \
  --with-included-unistring --without-p11-kit --disable-doc --disable-tests --disable-tools --disable-cxx \
  --disable-maintainer-mode --disable-libdane --prefix=$INSTALLDIR --disable-hardware-acceleration
make -j$(nproc)
make install
cd ..

# Install Libmicrohttpd from source
if [ ! -d libmicrohttpd ]; then
  git clone --recursive https://gnunet.org/git/libmicrohttpd.git
  cd libmicrohttpd
else
  cd libmicrohttpd
  git pull
fi
./bootstrap
./configure --build=x86_64-pc-linux-gnu --host=$PREFIX --prefix=$INSTALLDIR --disable-doc --disable-examples --enable-shared
make clean
make -j1 V=1
make install
cd ..
