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

_realname=hdf
pkgbase=mingw-w64-${_realname}4
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}4")
pkgver=4.3.0
pkgrel=1
pkgdesc="Legacy HDF4 driver for GDAL (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://github.com/HDFGroup/hdf4'
license=('spdx:BSD-3-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-libjpeg-turbo"
         "${MINGW_PACKAGE_PREFIX}-zlib"
         $([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran")
         )
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-fc")
source=(https://github.com/HDFGroup/hdf4/releases/download/hdf${pkgver}/hdf${pkgver}.tar.gz
        001-mingw.patch)
sha256sums=('282b244a819790590950f772095abcaeef405b0f17d2ee1eb5039da698cf938b'
            '0c3dd6ead089d752a6762fa7e7e79128fd2cc94a7bb0df194b12caac3002f130')

prepare() {
  cd "${srcdir}"/hdfsrc
  patch -p1 -i "${srcdir}"/001-mingw.patch
}

build() {
  mkdir -p "${srcdir}"/build-${MSYSTEM} && cd "${srcdir}"/build-${MSYSTEM}

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DBUILD_SHARED_LIBS=ON \
    -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
    -DHDF4_BUILD_TOOLS=OFF \
    -DHDF4_BUILD_UTILS=ON \
    -DHDF4_BUILD_FORTRAN=ON \
    -DHDF4_NO_PACKAGES=ON \
    -DHDF4_ENABLE_NETCDF=OFF \
    -DHDF4_INSTALL_INCLUDE_DIR="include/hdf4" \
    -DHDF4_INSTALL_CMAKE_DIR="lib/cmake/hdf4" \
    -DHDF4_INSTALL_DATA_DIR="share/docs/hdf4" \
    ../hdfsrc

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

package() {
  cd "${srcdir}"/build-${MSYSTEM}

  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --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

  install -Dm644 "${srcdir}/hdfsrc/COPYING" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}4/LICENSE"
}
