# Contributor: Mehdi Chinoune <mehdi.chinoune@hotmail.com>

_realname=gromacs
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=2025.1
pkgrel=2
pkgdesc="A free and open-source software suite for high-performance molecular dynamics and output analysis. (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='https://www.gromacs.org/'
msys2_repository_url="https://gitlab.com/gromacs/gromacs"
license=('spdx:LGPL-2.1-or-later')
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs"
         "${MINGW_PACKAGE_PREFIX}-fftw"
         "${MINGW_PACKAGE_PREFIX}-muparser"
         "${MINGW_PACKAGE_PREFIX}-omp"
         "${MINGW_PACKAGE_PREFIX}-opencl-icd"
         "${MINGW_PACKAGE_PREFIX}-openblas")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-opencl-headers"
             "${MINGW_PACKAGE_PREFIX}-python")
source=("https://ftp.gromacs.org/gromacs/${_realname}-${pkgver}.tar.gz"
        "001-fix-pkgconfig-file.patch"
        "002-fix-missing-define.patch")
noextract=("${_realname}-${pkgver}.tar.gz")
sha256sums=('0adf621a80fd8043f8defec84ce02811c0cdf42a052232890932d81f25c4d28a'
            '5ecd85134a454de8d1b0f9ba94fcd54c005d47ea162b776a596dc42451dbc632'
            '7e29701fc4872ca4e33bc91d3e7bf77d14c803fb146a65c23b7c1c4d84a1b1fd')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  tar -xzf "${_realname}-${pkgver}.tar.gz" || true

  cd "${srcdir}"/${_realname}-${pkgver}

  apply_patch_with_msg \
    001-fix-pkgconfig-file.patch \
    002-fix-missing-define.patch
}

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

  if [[ ${CARCH} == x86_64 ]]; then
    _extra_config+=("-DGMX_SIMD=AVX2_128")
  else # aarch64
    _extra_config+=("-DGMX_SIMD=ARM_NEON_ASIMD")
  fi

  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 \
      -DGMX_GPU=OpenCL \
      -DGMX_OPENMP=ON \
      -DGMX_FFT_LIBRARY=fftw3 \
      -DGMX_EXTERNAL_BLAS=ON \
      -DGMX_EXTERNAL_LAPACK=ON \
      -DGMX_USE_MUPARSER=EXTERNAL \
      -DBUILD_TESTING=OFF \
      -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python \
      -S "${_realname}-${pkgver}" \
      -B "build-${MSYSTEM}"

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

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

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