# Maintainer: Konstantin Podsvirov <konstantin@podsvirov.su>

_realname=mosquitto
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.0.22
pkgrel=1
pkgdesc="An Open Source MQTT Broker (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://mosquitto.org"
msys2_repository_url="https://github.com/eclipse-mosquitto/mosquitto"
msys2_references=(
  "cpe: cpe:/a:eclipse:mosquitto"
)
license=('spdx:EPL-2.0 OR EDL-1.0')
depends=("${MINGW_PACKAGE_PREFIX}-c-ares"
         "${MINGW_PACKAGE_PREFIX}-cjson"
         "${MINGW_PACKAGE_PREFIX}-libwebsockets"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread"
         "${MINGW_PACKAGE_PREFIX}-openssl")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-winpthreads"
             "${MINGW_PACKAGE_PREFIX}-docbook-xsl")
source=("https://mosquitto.org/files/source/mosquitto-${pkgver}.tar.gz"{,.asc}
        '0001-mosquitto-2.0.18-fix-static-libname.patch'
        '0002-mosquitto-2.0.18-pkgconf-static-cflags.patch'
        '0003-use-winpthreads.patch')
sha256sums=('2f752589ef7db40260b633fbdb536e9a04b446a315138d64a7ff3c14e2de6b68'
            'SKIP'
            '9be6dc259d3507a5c3d8d1da01555bdcac0e8e5d7619bb1a889c977611d4f914'
            'c19505bec196a82c1c7955314355645eba737998cc99468a2c9836843c8a7c06'
            '2d771a908b7a128bdaf5e082d7ac3cab3b8d4160b07cf6ebc99950986d957b42')
validpgpkeys=('A0D6EEA1DCAE49A635A3B2F0779B22DFB3E717B7') # Roger A. Light <roger@atchoo.org>

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"

  patch -p1 -i "${srcdir}/0001-mosquitto-2.0.18-fix-static-libname.patch"
  patch -p1 -i "${srcdir}/0002-mosquitto-2.0.18-pkgconf-static-cflags.patch"
  # It's trying to use Pthreads4W, which we don't have 
  patch -p1 -i "${srcdir}/0003-use-winpthreads.patch"
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/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 [[ $MINGW_PACKAGE_PREFIX != *-clang-* ]]; then
    CFLAGS+=" -Wno-incompatible-pointer-types"
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    ${_extra_config[@]} \
    -DCMAKE_INSTALL_SBINDIR=bin \
    -DWITH_STATIC_LIBRARIES=ON \
    -DWITH_PIC=ON \
    ../${_realname}-${pkgver}

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

check() {
  cd "${srcdir}/build-${MSYSTEM}"

  ${MINGW_PREFIX}/bin/ctest ./ || true
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install ./

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