# Maintainer: Olivier Xillo <oxillo++dev@mailo.com>

_realname=c4core
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=0.2.11
pkgrel=2
pkgdesc="Multiplatform low-level C++ utilities (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url="https://github.com/biojppm/c4core"
msys2_repository_url='https://github.com/biojppm/c4core'
license=('spdx:MIT' 'spdx:BSL-1.0')
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-cc"
             'git')
source=("${_realname}"::"git+https://github.com/biojppm/c4core.git#tag=v${pkgver}")
sha256sums=('a392ed3172f64a79a5a2df0cd2452525e27f3d520f46c5b7c003725da8b2a32e')

prepare() {
  # The git source clones are named after their definition in the source array.
  cd "${_realname}"

  # Configure and update the main submodule (c4core)
  git submodule init
  git submodule update

  # Apply any necessary patch for the build system (e.g., Python pathing fixes)
  # NOTE: This patch command is commented out because makepkg failed to find the source file.
  # If the build fails without it, you must place 'rapidyaml-python-bindings.patch'
  # in the same directory as the PKGBUILD and uncomment these lines.
  # patch -p1 < "${srcdir}/rapidyaml-python-bindings.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 \
      -G Ninja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=OFF \
      -S "${_realname}" \
      -B "build-${MSYSTEM}-static"

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

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -G Ninja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      -S "${_realname}" \
      -B "build-${MSYSTEM}-shared"

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

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

  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}-shared"

  # Install license
  install -Dm644 "${srcdir}/${_realname}/LICENSE.txt" \
    "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE.txt"
  install -Dm644 "${srcdir}/${_realname}/LICENSE-BOOST.txt" \
    "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE-BOOST.txt"
}
