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

_realname=cp2k
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=2025.1
pkgrel=1
pkgdesc="A quantum chemistry and solid state physics software package (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64')
url='https://www.cp2k.org'
msys2_repository_url="https://github.com/cp2k/cp2k"
license=('spdx:GPL-2.0-or-later')
depends=("${MINGW_PACKAGE_PREFIX}-fftw"
         "${MINGW_PACKAGE_PREFIX}-dbcsr"
         $([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran")
         "${MINGW_PACKAGE_PREFIX}-libint2"
         "${MINGW_PACKAGE_PREFIX}-libxc"
         "${MINGW_PACKAGE_PREFIX}-omp"
         "${MINGW_PACKAGE_PREFIX}-openblas"
         "${MINGW_PACKAGE_PREFIX}-spglib")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-fc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             #$([[ ${CARCH} != x86_64 ]] || echo "${MINGW_PACKAGE_PREFIX}-libxsmm")
             "${MINGW_PACKAGE_PREFIX}-python")
source=("https://github.com/cp2k/cp2k/releases/download/v${pkgver}/${_realname}-${pkgver}.tar.bz2"
        "001-fix-build-on-mingw-w64.patch")
sha256sums=('65c8ad5488897b0f995919b9fa77f2aba4b61677ba1e3c19bb093d5c08a8ce1d'
            'd60efc3d43e55aef81480794b698ccbcb40cf4d936859ac64b69436c00dc713d')

prepare() {
  cd ${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/001-fix-build-on-mingw-w64.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+=("-DCP2K_USE_LIBXSMM=ON")
  # else
  #   _extra_config+=("-DCP2K_USE_LIBXSMM=OFF")
  # fi

  FFLAGS=" -D__MINGW -D__NO_STATM_ACCESS -D__NO_SOCKETS" \
  CFLAGS+=" -D__NO_SOCKETS" \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    "${MINGW_PREFIX}"/bin/cmake.exe \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${_extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -DCP2K_USE_LIBINT2=ON \
      -DCP2K_USE_LIBXC=ON \
      -DCP2K_USE_SPGLIB=ON \
      -DCP2K_USE_MPI=OFF \
      -DCP2K_BLAS_VENDOR=OpenBLAS \
      -DPython_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}/LICENSE \
    "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
