# Maintainer: Andrew Sun <adsun701@gmail.com>

_realname=minizip
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}2")
pkgver=2.7.0
pkgrel=2
pkgdesc="Minizip zlib contribution fork with latest bug fixes that supports PKWARE disk splitting, AES encryption, and IO buffering (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32')
url='https://github.com/nmoinvaz/minizip/'
license=('ZLIB')
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-gcc")
depends=("${MINGW_PACKAGE_PREFIX}-bzip2"
         "${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-zlib")
source=("${_realname}-${pkgver}.tar.gz"::https://github.com/nmoinvaz/minizip/archive/${pkgver}.tar.gz
        001-library-name-compatibility.patch
        002-fix-pkg-config-file.patch)
sha256sums=('bfd57ec5990894e4b6a136d1e7cb11c69801cd962f9f1b2a90dbf0970aab73a6'
            '48725b345fa5f4dfa40af6751cea0b3dd7816c91e9da6b4df55e9bad02bdcc63'
            '4b44742624211a6fb7fc7e8b5ad4592f45e340105e8624d57fe1edd78d82f843')

prepare() {
  cd "${srcdir}"/${_realname}-ng-${pkgver}
  patch -p1 -i ${srcdir}/001-library-name-compatibility.patch
  patch -p1 -i ${srcdir}/002-fix-pkg-config-file.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

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

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
      -G'MSYS Makefiles' \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      -DUSE_ZLIB=ON \
      -DUSE_BZIP2=ON \
      -DUSE_LZMA=ON \
      -DUSE_PKCRYPT=ON \
      -DUSE_AES=ON \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=ON \
      ../${_realname}-ng-${pkgver}
  make

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

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake \
      -G'MSYS Makefiles' \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      -DUSE_ZLIB=ON \
      -DUSE_BZIP2=ON \
      -DUSE_LZMA=ON \
      -DUSE_PKCRYPT=ON \
      -DUSE_AES=ON \
      "${extra_config[@]}" \
      -DBUILD_SHARED_LIBS=OFF \
      ../${_realname}-ng-${pkgver}
  make
}

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

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

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

  install -Dm0644 ${srcdir}/${_realname}-ng-${pkgver}/LICENSE ${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE
}
