_realname=libwebm
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.0.0.27
pkgrel=2
pkgdesc="WebM video file parser (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://chromium.googlesource.com/webm/libwebm"
license=('BSD')
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=(https://github.com/webmproject/${_realname}/archive/refs/tags/${_realname}-${pkgver}.tar.gz
        msys2_changes.patch
        missing_includes.patch
        libwebm.pc)
sha256sums=('1332f43742aeae215fd8df1be6e363e753b17abb37447190e789299fe3edec77'
            '61c1822a1c4e7636c69e8658676a4a5c4c4e4b2372294d811ddef4171c47516d'
            '05a78fbba1d55d7d6cd10961841dd130111d8efb380bb30ed33f78335a0d4193'
            'db828721772782ccf87c37179eecfc4ba95c466104320cf21e31af324ef4a8d2')

prepare() {
  cd ${srcdir}/${_realname}-${_realname}-${pkgver}
  patch -p1 -i ${srcdir}/msys2_changes.patch
  patch -p1 -i ${srcdir}/missing_includes.patch
}

build() {
  if [[ ${MINGW_PACKAGE_PREFIX} == *-clang-* ]]; then
    CXXFLAGS+=" -Wno-c++11-narrowing"
  else
    CXXFLAGS+=" -Wno-narrowing"
  fi

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

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -Wno-dev \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_BUILD_TYPE=Release \
    ../${_realname}-${_realname}-${pkgver}

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

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

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -Wno-dev \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_BUILD_TYPE=Release \
    -DBUILD_SHARED_LIBS=ON \
    ../${_realname}-${_realname}-${pkgver}

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

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

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

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

  cd ${srcdir}
  sed -i "s|TO_BE_REPLACED|${MINGW_PREFIX}|g" libwebm.pc
  install -Dm644 libwebm.pc "$pkgdir${MINGW_PREFIX}/lib/pkgconfig/libwebm.pc"
}
