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

_realname=libpcap
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.10.1
pkgrel=2
pkgdesc="A system-independent interface for user-level packet capture (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://www.tcpdump.org/"
license=('BSD')
depends=("${MINGW_PACKAGE_PREFIX}-openssl")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
options=('strip' '!debug' 'staticlibs')
source=("https://www.tcpdump.org/release/${_realname}-${pkgver}.tar.gz"{,.sig}
        "0001-cmake-install-rpcapd-bindir.patch"
        "0002-cmake-keep-lib-prefixed-dll.patch"
        "0003-charconv-include-errno.patch")
sha256sums=('ed285f4accaf05344f90975757b3dbfe772ba41d1c401c2648b7fa45b711bdd4'
            'SKIP'
            'ded3f2a43e168fba35166630b6e5f9ef95c01feb2f7bf1f035d794f41af4dfeb'
            '09dfe0f962a99df7d1d8fdb9bb9b320b6d33e0a7c2efec136065a7b359de188d'
            '8a7faa97e85adc8fb532499205224e94e4d2b77693e42666f6c2bd48c9f38571')
validpgpkeys=('1F166A5742ABB9E0249A8D30E089DEF1D9C15D0D') # The Tcpdump Group

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  patch -Np1 -i "${srcdir}/0001-cmake-install-rpcapd-bindir.patch"
  patch -Np1 -i "${srcdir}/0002-cmake-keep-lib-prefixed-dll.patch"
  patch -Np1 -i "${srcdir}/0003-charconv-include-errno.patch"
}

build() {
  [[ -d "${srcdir}/build-${MINGW_CHOST}" ]] && rm -rf "${srcdir}/build-${MINGW_CHOST}"
  mkdir -p "${srcdir}/build-${MINGW_CHOST}" && cd "${srcdir}/build-${MINGW_CHOST}"

  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 \
    -G "Ninja" \
    -Wno-dev \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DDISABLE_DBUS=ON \
    "../${_realname}-${pkgver}"

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

check() {
  cd "${srcdir}/build-${MINGW_CHOST}"
  ${MINGW_PREFIX}/bin/ctest.exe ./ || true
}

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

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for pcfile in "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pcfile}"
  done
  sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pkgdir}${MINGW_PREFIX}"/bin/pcap-config

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