# Maintainer: Marty Plummer (The_NetZ) <ntzrmtthihu777 (at) gmail (dot) com>

_realname=SDL2_image
pkgbase=mingw-w64-${_realname}
pkgname=${MINGW_PACKAGE_PREFIX}-${_realname}
pkgver=2.8.8
pkgrel=1
pkgdesc="A simple library to load images of various formats as SDL surfaces (Version 2) (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/libsdl-org/SDL_image"
msys2_references=(
  "cpe: cpe:/a:libsdl:sdl2_image"
)
license=('spdx:Zlib')
depends=("${MINGW_PACKAGE_PREFIX}-SDL2"
         "${MINGW_PACKAGE_PREFIX}-libavif"
         "${MINGW_PACKAGE_PREFIX}-libjxl"
         "${MINGW_PACKAGE_PREFIX}-libpng"
         "${MINGW_PACKAGE_PREFIX}-libtiff"
         "${MINGW_PACKAGE_PREFIX}-libjpeg-turbo"
         "${MINGW_PACKAGE_PREFIX}-libwebp")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc" "${MINGW_PACKAGE_PREFIX}-autotools")
source=("https://github.com/libsdl-org/SDL_image/releases/download/release-${pkgver}/SDL2_image-${pkgver}.zip"{,.sig})
sha256sums=('def4c7cba37a2f2cce83cfeff053220b2e1481c3c00d59638b1c526ae58545ac'
            'SKIP')
validpgpkeys=('1528635D8053A57F77D1E08630A59377A7763BE6') # Sam Lantinga <slouken@libsdl.org>

build() {
  local -a _common_config
  _common_config+=(
    --disable-avif-shared
    --disable-jpg-shared
    --disable-jxl-shared
    --disable-png-shared
    --disable-stb-image
    --disable-tif-shared
    --disable-webp-shared
  )

  mkdir -p "${srcdir}/build-${MSYSTEM}-static" && cd "${srcdir}/build-${MSYSTEM}-static"

  CPPFLAGS+=" -DJXL_STATIC_DEFINE" \
  ../${_realname}-${pkgver}/configure \
    --prefix=${MINGW_PREFIX} \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --enable-static \
    --disable-shared \
    "${_common_config[@]}"

  # Remove AVIF_DLL macro to prevent adding dllimport attribute for static linking
  find . -name Makefile -exec sed -i "s/-DAVIF_DLL//g" {} \;

  make

  mkdir -p "${srcdir}/build-${MSYSTEM}-shared" && cd "${srcdir}/build-${MSYSTEM}-shared"

  ../${_realname}-${pkgver}/configure \
    --prefix=${MINGW_PREFIX} \
    --build=${MINGW_CHOST} \
    --host=${MINGW_CHOST} \
    --enable-shared \
    --disable-static \
    "${_common_config[@]}"

  make
}

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

  cd "${srcdir}/build-${MSYSTEM}-shared"
  make DESTDIR="${pkgdir}" install

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/${_realname}/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
    sed -e "s|${MINGW_PREFIX}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done

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