# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Maintainer: Ray Donnelly <mingw.android@gmail.com>

_realname=tesseract-ocr
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=4.1.1
pkgrel=7
pkgdesc="Tesseract OCR (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64')
url="https://github.com/tesseract-ocr/tesseract"
license=("Apache License 2.0")
makedepends=("${MINGW_PACKAGE_PREFIX}-gcc" "${MINGW_PACKAGE_PREFIX}-pkg-config")
depends=(${MINGW_PACKAGE_PREFIX}-cairo
         ${MINGW_PACKAGE_PREFIX}-curl
         ${MINGW_PACKAGE_PREFIX}-gcc-libs
         ${MINGW_PACKAGE_PREFIX}-icu
         ${MINGW_PACKAGE_PREFIX}-leptonica
         ${MINGW_PACKAGE_PREFIX}-libarchive
         ${MINGW_PACKAGE_PREFIX}-pango
         ${MINGW_PACKAGE_PREFIX}-zlib)
options=('!libtool' 'strip')
source=(${_realname}-${pkgver}.tar.gz::https://github.com/tesseract-ocr/tesseract/archive/${pkgver}.tar.gz
        https://github.com/tesseract-ocr/tessdata_fast/raw/master/osd.traineddata
        tesseract-no-as-needed.patch)
sha256sums=('2a66ff0d8595bff8f04032165e6c936389b1e5727c3ce5a27b3e059d218db1cb'
            '9cf5d576fcc47564f11265841e5ca839001e7e6f38ff7f7aacf46d15a96b00ff'
            '60aa311301015e78a96edb228db160fe10784e074f45ef3d7e6ecbc8d52eb388')

prepare() {
  cd "${srcdir}/tesseract-${pkgver}"
  patch -p1 -i "${srcdir}/tesseract-no-as-needed.patch"

  ./autogen.sh
}

build() {
  [[ -d "${srcdir}/build-${MINGW_CHOST}" ]] && rm -rf "${srcdir}/build-${MINGW_CHOST}"
  mkdir "${srcdir}/build-${MINGW_CHOST}"
  cd "${srcdir}/build-${MINGW_CHOST}"
  local -a extra_config
  if check_option "debug" "y"; then
    extra_config+=( --enable-debug )
  fi

  # tesseract 4.1.1: skip creating the documentation by
  #   pretending that asciidoc is not available, since
  #   otherwise running make results in an error
  ac_cv_prog_have_asciidoc=no      \
  ../tesseract-${pkgver}/configure \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --target=${MINGW_CHOST} \
    --prefix=${MINGW_PREFIX} \
    LIBLEPT_HEADERSDIR=${MINGW_PREFIX}/include \
    "${extra_config[@]}"

  make
  make training
}

check() {
  cd "${srcdir}/build-${MINGW_CHOST}"
  make -j1 check || true
}

package() {
  cd "${srcdir}/build-${MINGW_CHOST}"
  make DESTDIR="${pkgdir}" install
  make DESTDIR="${pkgdir}" training-install
  mkdir -p ${pkgdir}${MINGW_PREFIX}/share/tessdata
  install -Dm0644 ${srcdir}/osd.traineddata ${pkgdir}${MINGW_PREFIX}/share/tessdata/osd.traineddata

  # Fix .pc file
  sed -s "/^Libs:/ { s|$(cygpath -m ${MINGW_PREFIX})|${MINGW_PREFIX}|g }" -i "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/tesseract.pc
}
