# Maintainer: Christoph Reiter <reiter.christoph@gmail.com>

_realname=cjson
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.7.19
pkgrel=1
pkgdesc="Ultralightweight JSON parser in ANSI C (mingw-w64)"
arch=(any)
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/DaveGamble/cJSON"
msys2_repository_url="https://github.com/DaveGamble/cJSON"
msys2_references=(
  "cpe: cpe:/a:cjson_project:cjson"
)
license=('spdx:MIT')
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/DaveGamble/cJSON/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        "001-fix-cmake-files.patch")
sha256sums=('7fa616e3046edfa7a28a32d5f9eacfd23f92900fe1f8ccd988c1662f30454562'
            'f7a5e88c13d58806876dac5d2e255812bee7837cfe7214c9fe8e0f57edb5c25d')

prepare() {
  cd ${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/001-fix-cmake-files.patch
}

build() {
  mkdir -p build-${MSYSTEM} && cd build-${MSYSTEM}

  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 [[ ${MSYSTEM} == CLANG* ]]; then
    CFLAGS+=" -Wno-error=used-but-marked-unused"
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  cmake \
    -G Ninja \
    "${_extra_config[@]}" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DENABLE_CJSON_TEST=OFF \
    -DBUILD_SHARED_AND_STATIC_LIBS=ON \
    -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
    -DENABLE_CJSON_UTILS=ON \
    -DCMAKE_POLICY_VERSION_MINIMUM=3.5 \
    ../${_realname}-${pkgver}

  cmake --build .
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  DESTDIR="${pkgdir}" cmake --install .

  for pcfile in  "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${MINGW_PREFIX}|\${prefix}|g" -i "${pcfile}"
    sed -i "1s|^|prefix=${MINGW_PREFIX}\\n|" "${pcfile}"
  done

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