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

_realname=dftd4
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=3.7.0
pkgrel=1
pkgdesc="Generally Applicable Atomic-Charge Dependent London Dispersion Correction. (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='https://dftd4.readthedocs.io/'
msys2_repository_url="https://github.com/dftd4/dftd4"
license=('spdx:LGPL-3.0-or-later')
depends=($([[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]] || echo "${MINGW_PACKAGE_PREFIX}-gcc-libgfortran")
         "${MINGW_PACKAGE_PREFIX}-mctc-lib"
         "${MINGW_PACKAGE_PREFIX}-multicharge"
         "${MINGW_PACKAGE_PREFIX}-omp"
         "${MINGW_PACKAGE_PREFIX}-openblas")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-fc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-mstore")
source=("https://github.com/dftd4/dftd4/releases/download/v${pkgver}/dftd4-${pkgver}.tar.xz"
        "001-fix-install-dll.patch")
sha256sums=('4e8749df6852bf863d5d1831780a2d30e9ac4afcfebbbfe5f6a6a73d06d6c6ee'
            '0b1aa039690c43ecf1a59b099d0e44b2a3c9584065325e3896ffe5728d7e4e5b')

prepare() {
  cd "${_realname}-${pkgver}"

  patch -Np1 -i "${srcdir}"/001-fix-install-dll.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

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
      -DWITH_API=ON \
      -S "${_realname}-${pkgver}" \
      -B "build-${MSYSTEM}"

  cmake --build "build-${MSYSTEM}"
}

check() {
  PATH="${srcdir}"/build-${MSYSTEM}:"${srcdir}"/build-${MSYSTEM}/subprojects/multicharge:$PATH \
  ctest --test-dir "build-${MSYSTEM}" --output-on-failure
}

package() {
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}"

  # Fix CMake file
  sed -e "s|${MINGW_PREFIX}|\$\{PACKAGE_PREFIX_DIR\}|g" \
    -i "${pkgdir}"${MINGW_PREFIX}/lib/cmake/dftd4/dftd4-config.cmake
}
