# Maintainer: Jeroen Ooms <jeroen@berkeley.edu>

_realname=hdf
pkgbase=mingw-w64-${_realname}4
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}4")
pkgver=4.2.15
pkgrel=3
pkgdesc="Legacy HDF4 driver for GDAL (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64')
url='https://support.hdfgroup.org/products/hdf4/'
license=('GPL2')
source=(#"https://support.hdfgroup.org/ftp/HDF/HDF_Current/src/${_realname}-${pkgver}.tar.gz"
        "https://support.hdfgroup.org/ftp/HDF/releases/HDF${pkgver}/src/hdf-${pkgver}.tar.bz2"
        001-mingw.patch
        002-pkgconfig-without-versioning.patch)
sha256sums=('bde035ef5a1cd5fdbd0a7f1fa5c17e98bbd599300189ac4d234f16e9bb7bcb12'
            'f842fb5efe99b8ad3e4ecb7683af106c4891d994abb44adf8fd34a54cb729a38'
            '0362725aa964bff6318d37740481e462d77c2d1c39cccc86690773de3d69e94c')
depends=("${MINGW_PACKAGE_PREFIX}-libjpeg-turbo"
         "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran"
         "${MINGW_PACKAGE_PREFIX}-zlib")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-gcc-fortran")
options=('strip' 'staticlibs')

prepare() {
  cd ${srcdir}/${_realname}-${pkgver}
  patch -p1 -i ${srcdir}/001-mingw.patch
  patch -p1 -i ${srcdir}/002-pkgconfig-without-versioning.patch
}

build() {
  [[ -d "${srcdir}"/build-${CARCH} ]] && rm -rf "${srcdir}"/build-${CARCH}
  mkdir -p "${srcdir}"/build-${CARCH} && cd "${srcdir}"/build-${CARCH}

  if [[ ${MINGW_PACKAGE_PREFIX} != *-clang-* ]]; then
    export FFLAGS="-fallow-argument-mismatch"
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_BUILD_TYPE="Release" \
    -DBUILD_SHARED_LIBS=ON \
    -DHDF4_BUILD_TOOLS=OFF \
    -DHDF4_BUILD_UTILS=ON \
    -DHDF4_BUILD_FORTRAN=ON \
    -DHDF4_NO_PACKAGES=ON \
    -DHDF4_ENABLE_NETCDF=OFF \
    -DHDF4_INSTALL_CMAKE_DIR="lib/cmake" \
    -DHDF4_INSTALL_DATA_DIR="share/docs/hdf4" \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

package() {
  cd "${srcdir}"/build-${CARCH}
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --build ./ --target install

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/hdf4/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done

  for pcfile in "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pcfile}"
  done
  sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pkgdir}${MINGW_PREFIX}"/lib/libhdf4.settings
}
