# Maintainer: Zheng Xueke <xueke0114@foxmail.com>

_realname=netcdf-fortran
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=4.6.1
pkgrel=3
pkgdesc="Unidata NetCDF Fortran Library (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://docs.unidata.ucar.edu/netcdf-fortran/current/"
msys2_repository_url="https://github.com/Unidata/netcdf-fortran"
license=('spdx:Apache-2.0')
depends=("${MINGW_PACKAGE_PREFIX}-netcdf"
         "${MINGW_PACKAGE_PREFIX}-libxml2"
         $([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran"))
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-fc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/Unidata/${_realname}/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz")
sha256sums=('40b534e0c81b853081c67ccde095367bd8a5eead2ee883431331674e7aa9509f')

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

  HDF5_PLUGIN_PATH="${MINGW_PREFIX}"/lib \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  "${MINGW_PREFIX}"/bin/cmake.exe \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
    "${extra_config[@]}" \
    -DBUILD_SHARED_LIBS=ON \
    -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
    -DNF_M4="" \
    ../${_realname}-${pkgver}

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

check(){
  cd "${srcdir}/build-${MSYSTEM}"
  
  PATH="${srcdir}/build-${MSYSTEM}/fortran/":$PATH \
  "${MINGW_PREFIX}"/bin/ctest
}

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

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/netCDF/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done
  sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pkgdir}${MINGW_PREFIX}"/bin/nf-config
  sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pkgdir}${MINGW_PREFIX}"/lib/libnetcdff.settings
  sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/netcdf-fortran.pc

  # Remove unwanted artifacts https://github.com/Unidata/netcdf-fortran/issues/338
  rmdir "${pkgdir}"${MINGW_PREFIX}/include/CMakeFiles/{netcdff{,_c}.dir,}
  rm "${pkgdir}"${MINGW_PREFIX}/lib/objects-RelWithDebInfo/{nf_,f}test_c/f03lib.c.obj
  rmdir "${pkgdir}"${MINGW_PREFIX}/lib/objects-RelWithDebInfo/{{nf_,f}test_c,}
  rm "${pkgdir}"${MINGW_PREFIX}/lib/objects-Release/netcdff_c/nf_{lib,v2compat}.c.obj
  rmdir "${pkgdir}"${MINGW_PREFIX}/lib/objects-Release/{netcdff_c,}

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/COPYRIGHT" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/COPYRIGHT"
}
