#! /usr/bin/bash


_realname=igraph
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=0.9.4
pkgrel=1
pkgdesc="Library for the analysis of networks (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://igraph.org"
license=('GPL')
source=("https://github.com/igraph/igraph/releases/download/${pkgver}/igraph-${pkgver}.tar.gz"
        '0001-igraph-0.9.3-igraph.pc.in-add-member-Cflags.private.patch')
sha256sums=('a3285cccf4f043c9ced2bc8d8d2609ff8398cb92ed49fdf86264ed91929137dd'
            '53e4ae45a640c10467ceaf939c78a3d27b87f1078db7555cf7acafa798a29c27')
depends=("${MINGW_PACKAGE_PREFIX}-libxml2"
         "${MINGW_PACKAGE_PREFIX}-zlib")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")

_srcdir=${_realname}-${pkgver}
_builddir=build-${pkgver}-${MINGW_PACKAGE_PREFIX}
# Keep _libtypes in THIS order to ensure that header file 'igraph_export.h'
#  works for both the static and the shared library after installation.
_libtypes='static shared'

prepare() {
  cd ${_srcdir}
  patch -p1 -b -i "${srcdir}/0001-igraph-0.9.3-igraph.pc.in-add-member-Cflags.private.patch"
}

build() {
  for libtype in ${_libtypes}; do
    case $libtype in
      (static) _BUILD_SHARED_LIBS=OFF;;
      (shared) _BUILD_SHARED_LIBS=ON;;
      (*) exit 1
    esac
    mkdir -p ${_builddir}-${libtype}
    pushd ${_builddir}-${libtype}
      MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
      ${MINGW_PREFIX}/bin/cmake ../${_srcdir} \
        -G 'Ninja' \
        -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
        -DBUILD_SHARED_LIBS=${_BUILD_SHARED_LIBS} \
        -DCMAKE_BUILD_TYPE=Release \
        -DIGRAPH_ENABLE_TLS=1 \
        -DIGRAPH_GLPK_SUPPORT=1 \
        -DIGRAPH_GRAPHML_SUPPORT=1 \
        -DIGRAPH_USE_INTERNAL_ARPACK=1 \
        -DIGRAPH_USE_INTERNAL_BLAS=1 \
        -DIGRAPH_USE_INTERNAL_CXSPARSE=1 \
        -DIGRAPH_USE_INTERNAL_GLPK=1 \
        -DIGRAPH_USE_INTERNAL_GMP=1 \
        -DIGRAPH_USE_INTERNAL_LAPACK=1

      cmake --build . || cmake --verbose --build .
    popd
  done
}

check() {
  # igraph 0.9.4: All tests succeeded.
  for libtype in ${_libtypes}; do
    ${MINGW_PREFIX}/bin/cmake --build ${_builddir}-${libtype} --target build_tests
    ${MINGW_PREFIX}/bin/ctest --test-dir ${_builddir}-${libtype} --output-on-failure
  done
}

package() {
  # Install the libtypes one over another (until the simultaneous build of
  # shared and static libraries is implemented). :(
  for libtype in ${_libtypes}; do
    DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --build ${_builddir}-${libtype} --target install
  done

  # Remove cmake files to avoid confusion when both shared and
  # static library are installed.
  pushd "${pkgdir}${MINGW_PREFIX}/lib"
    rm -fr 'cmake'
  popd

  install -D -m644 ${_srcdir}/COPYING "${pkgdir}"/${MSYSTEM_PREFIX}/share/licenses/${_realname}/COPYING
}
