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

_realname=coordgen
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=3.0.2
pkgrel=1
pkgdesc="Schrodinger-developed 2D Coordinate Generation. (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='https://github.com/schrodinger/coordgenlibs'
msys2_references=(
  'archlinux: coordgen'
)
license=('spdx:BSD-3-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs"
         "${MINGW_PACKAGE_PREFIX}-maeparser")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/schrodinger/coordgenlibs/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz")
sha256sums=('f67697434f7fec03bca150a6d84ea0e8409f6ec49d5aab43badc5833098ff4e3')

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=" \
    "${MINGW_PREFIX}"/bin/cmake.exe \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${_extra_config[@]}" \
      -DCOORDGEN_BUILD_SHARED_LIBS=ON \
      -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
      -DCOORDGEN_USE_MAEPARSER=ON \
      -DCOORDGEN_RIGOROUS_BUILD=OFF \
      -DCOORDGEN_BUILD_TESTS=OFF \
      -DCOORDGEN_BUILD_EXAMPLE=OFF \
      -S "coordgenlibs-${pkgver}" \
      -B "build-${MSYSTEM}"

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

check() {
  "${MINGW_PREFIX}"/bin/cmake.exe \
    -Bbuild-${MSYSTEM} \
    -Scoordgenlibs-${pkgver} \
    -DCOORDGEN_BUILD_TESTS=ON \
    -DCOORDGEN_BUILD_EXAMPLE=ON 
  "${MINGW_PREFIX}"/bin/cmake.exe --build build-${MSYSTEM}

  PATH="${srcdir}"/build-${MSYSTEM}:$PATH \
    "${MINGW_PREFIX}"/bin/ctest --test-dir build-${MSYSTEM} || echo "Tests failed"
}

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

  install -Dm644 "${srcdir}"/coordgenlibs-${pkgver}//templates.mae \
    -t "${pkgdir}"${MINGW_PREFIX}/share/coordgen
  install -Dm644 "${srcdir}"/coordgenlibs-${pkgver}/LICENSE \
    "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done
}
