# Maintainer: Biswapriyo Nath <nathbappai@gmail.com>

_realname=aws-c-common
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=0.5.5
pkgrel=1
pkgdesc="Core c99 package for AWS SDK for C. Includes cross-platform primitives, configuration, data structures, and error handling (mingw-w64)."
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://github.com/awslabs/aws-c-common"
license=('Apache-2.0')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
conflicts=("${MINGW_PACKAGE_PREFIX}-aws-sdk-cpp<1.8.149")
options=('strip' '!debug' 'staticlibs')
source=("${_realname}-${pkgver}.tar.gz"::"${url}/archive/v${pkgver}.tar.gz")
noextract=("${_realname}-${pkgver}.tar.gz")
sha256sums=('a60bb8aada37adcc3f66a3c6592723daef1cc17ddf8204956dd8e3f90742501d')

prepare() {
  [[ -d "${srcdir}/${_realname}-${pkgver}" ]] && rm -rf "${srcdir}/${_realname}-${pkgver}"
  tar -xf "${srcdir}/${_realname}-${pkgver}.tar.gz" -C "${srcdir}" 2>/dev/null || true

  cd "${srcdir}/${_realname}-${pkgver}"
  sed -i "s/ -Werror//g" cmake/AwsCFlags.cmake cmake/AwsFeatureTests.cmake
  sed -i "s/_MSC_VER/_WIN32/g" include/aws/common/byte_order.inl

  # For clang
  sed -i "s/-fPIC//g" cmake/AwsCFlags.cmake
}

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

  echo "Building static library"
  [[ -d "${srcdir}/build-${CARCH}-static" ]] && rm -rf "${srcdir}/build-${CARCH}-static"
  mkdir -p "${srcdir}/build-${CARCH}-static" && cd "${srcdir}/build-${CARCH}-static"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G "Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${extra_config[@]}" \
    -DBUILD_SHARED_LIBS=OFF \
    ../${_realname}-${pkgver}

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

  echo "Building shared library"
  [[ -d "${srcdir}/build-${CARCH}-shared" ]] && rm -rf "${srcdir}/build-${CARCH}-shared"
  mkdir -p "${srcdir}/build-${CARCH}-shared" && cd "${srcdir}/build-${CARCH}-shared"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G "Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${extra_config[@]}" \
    -DBUILD_SHARED_LIBS=ON \
    ../${_realname}-${pkgver}

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

package() {
  cd "${srcdir}/build-${CARCH}-static"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --build ./ --target install

  cd "${srcdir}/build-${CARCH}-shared"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --build ./ --target install

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