# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=leptonica
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.86.0
pkgrel=3
pkgdesc="An open source C library for efficient image processing and image analysis operations (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='http://www.leptonica.org'
msys2_repository_url='https://github.com/danbloomberg/leptonica'
msys2_references=(
  "archlinux: leptonica"
  "cpe: cpe:/a:leptonica:leptonica"
  "gentoo: media-libs/leptonica"
)
license=("spdx:BSD-2-Clause")
depends=(${MINGW_PACKAGE_PREFIX}-giflib
         ${MINGW_PACKAGE_PREFIX}-libjpeg-turbo
         ${MINGW_PACKAGE_PREFIX}-libpng
         ${MINGW_PACKAGE_PREFIX}-libtiff
         ${MINGW_PACKAGE_PREFIX}-libwebp
         ${MINGW_PACKAGE_PREFIX}-openjpeg2
         ${MINGW_PACKAGE_PREFIX}-zlib)
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
checkdepends=("${MINGW_PACKAGE_PREFIX}-gnuplot")
source=("https://github.com/DanBloomberg/leptonica/archive/${pkgver}/${_realname}-${pkgver}.tar.gz"
        "001-Fix-SOVERSION-on-mingw.patch"
        "002-Fix-pkgconfig-file-name.patch"
        "003-Fix-cmake-include-directories.patch"
        "https://github.com/DanBloomberg/leptonica/pull/778.patch")
sha256sums=('b4447faf61a8786a9b211d58d4103d85d47fd3a5dd418d5a6bc525d41db54ccc'
            '0bba2b4773083b09266b94e759801b07e787ef8bdc3458881202f06c23f03e8b'
            '6a9bde25199eba47e12d0013591fb4d376df386b1dccd252a8b64374e742f889'
            'd278ea2957025c9cc9bccbdbf1c757e1ce2f29d14287b0dfbcac02ebebc48f88'
            'f411e8f7a7bb7d4996c7e1e7e0f7ca49aae189e1269efd17b466fe9c069e020d')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd ${_realname}-${pkgver}
  apply_patch_with_msg \
    001-Fix-SOVERSION-on-mingw.patch \
    002-Fix-pkgconfig-file-name.patch \
    003-Fix-cmake-include-directories.patch \
    778.patch
}

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

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
    -DBUILD_SHARED_LIBS=ON \
    -DBUILD_PROG=ON \
    -DSW_BUILD=OFF \
    -DSTRICT_CONF=ON \
    "${_extra_config[@]}" \
    -S "${_realname}-${pkgver}" \
    -B build-${MSYSTEM}

  cmake --build build-${MSYSTEM}
}

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

  #ctest
}

package() {
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}"

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