# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Renato Silva <br.renatosilva@gmail.com>

_realname=libjpeg-turbo
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=2.0.6
pkgrel=1
pkgdesc="JPEG image codec with accelerated baseline compression and decompression (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url="https://libjpeg-turbo.virtualgl.org/"
license=(custom:'BSD-like')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-gcc"
             "${MINGW_PACKAGE_PREFIX}-nasm")
provides=("${MINGW_PACKAGE_PREFIX}-libjpeg")
conflicts=("${MINGW_PACKAGE_PREFIX}-libjpeg")
replaces=("${MINGW_PACKAGE_PREFIX}-libjpeg")
options=('staticlibs' 'strip')
source=(${_realname}-${pkgver}.tar.gz::https://github.com/libjpeg-turbo/libjpeg-turbo/archive/${pkgver}.tar.gz
        "0001-header-compat.mingw.patch"
        "libjpeg-turbo-1.3.1-libmng-compatibility.patch")
sha256sums=('005aee2fcdca252cee42271f7f90574dda64ca6505d9f8b86ae61abc2b426371'
            '166264f617734b33ac55ec8b70e6636d4e409c0d837667afe158e9d28200e6dd'
            '16336caddc949a8a082f39c218b3289288d144bb3b87f62565ed1b294ff8e526')

prepare() {
  cd "${srcdir}/${_realname}-${pkgver}"
  patch -p1 -i ${srcdir}/0001-header-compat.mingw.patch
  patch -p1 -i ${srcdir}/libjpeg-turbo-1.3.1-libmng-compatibility.patch
}

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

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
    -G"MSYS Makefiles" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_BUILD_TYPE=Release \
    -DWITH_JPEG8=ON \
    ../${_realname}-${pkgver}

  make
}

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

package() {
  cd "${srcdir}/build-${MINGW_CHOST}"
  make DESTDIR="${pkgdir}" install

  cp "${srcdir}"/${_realname}-${pkgver}/{jinclude,transupp}.h ${pkgdir}${MINGW_PREFIX}/include/

  # Licenses
  # See https://www.libjpeg-turbo.org/About/License
  cd "${srcdir}/${_realname}-${pkgver}"
  install -Dm644 README.ijg            "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/README.ijg"
  install -Dm644 README.md  "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/README.md"
  install -Dm644 simd/nasm/jsimdext.inc "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/simd/jsimdext.inc"
}
