# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Andrew Sun <adsun701@gmail.com>

_realname=c-ares
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.15.0
pkgrel=1
pkgdesc="C library that performs DNS requests and name resolves asynchronously (mingw-w64)"
arch=('any')
url="https://c-ares.haxx.se/"
license=("MIT, BSD")
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc" 
"${MINGW_PACKAGE_PREFIX}-pkg-config" "${MINGW_PACKAGE_PREFIX}-cmake")
options=('strip' 'staticlibs')
source=(#"https://c-ares.haxx.se/download/${_realname}-${pkgver}.tar.gz"{,.asc}
        https://github.com/c-ares/c-ares/archive/cares-${pkgver//./_}.tar.gz
        0001-Use-RPM-compiler-options.patch
        0002-Add-static-pkg-config.patch
        0003-fix-cmake-targets.patch)
validpgpkeys=('914C533DF9B2ADA2204F586D78E11C6B279D5C91'
              '27EDEAF22F3ABCEB50DB9A125CC908FDB71E12C2')
sha256sums=('7deb7872cbd876c29036d5f37e30c4cbc3cc068d59d8b749ef85bb0736649f04'
            'f00faa8723fd530b027f96b987ef19138628a49afdf52ffb0554b36156fc9d74'
            'f181a2556cf28a0cbc948cd58a7bcf0c3c3cef01370d0f0fa6b3915f62d05d56'
            '5810001abdd4acb8ae725dedb4d67874c3e2935775ecba30469a2a79c76fd6a0')

# Helper macros to help make tasks easier #
apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying $_patch"
    patch -Nbp1 -i "${srcdir}/$_patch"
  done
}

del_file_exists() {
  for _fname in "$@"
  do
    if [ -f $_fname ]; then
      rm -rf $_fname
    fi
  done
}
# =========================================== #

prepare() {
  cd "${srcdir}"/${_realname}-cares-${pkgver//./_}
  del_file_exists libcares-static.pc.in
  apply_patch_with_msg 0001-Use-RPM-compiler-options.patch \
    0002-Add-static-pkg-config.patch \
    0003-fix-cmake-targets.patch

  autoreconf -fi
}

build() {
  [[ -d "${srcdir}"/build-${CARCH} ]] && rm -rf "${srcdir}"/build-${CARCH}
  mkdir -p "${srcdir}"/build-${CARCH} && cd "${srcdir}"/build-${CARCH}
  
  ../${_realname}-cares-${pkgver//./_}/configure \
    --prefix=${MINGW_PREFIX} \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --enable-shared \
    --enable-static

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
      -Wno-dev \
      -G"MSYS Makefiles" \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      -DCMAKE_BUILD_TYPE="Release" \
      -DCARES_STATIC=ON \
      -DCARES_SHARED=ON \
      ../${_realname}-cares-${pkgver//./_}
}

package() {
  cd "${srcdir}"/build-${CARCH}
  make DESTDIR="${pkgdir}" install

  # msys2-runtime-devel provide nameser.h but mingw-w64 don't have it
  cp ${srcdir}/${_realname}-cares-${pkgver//./_}/nameser.h ${pkgdir}${MINGW_PREFIX}/include
  
  # provide pkgconfig files
  sed -i -e "s|Version: -|Version: ${pkgver}|g" libcares.pc libcares-static.pc
  install -Dm644 libcares.pc ${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/libcares.pc
  install -Dm644 libcares-static.pc ${pkgdir}${MINGW_PREFIX}/lib/pkgconfig/libcares-static.pc
}
