# Maintainer: taozuhong <taozuhong@gmail.com>

_realname=xlsxio
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.2.35
pkgrel=1
pkgdesc="C library for reading and writing .xlsx files(mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/brechtsanders/xlsxio"
license=("spdx:MIT")
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-cc"
  "${MINGW_PACKAGE_PREFIX}-cmake"
  "${MINGW_PACKAGE_PREFIX}-ninja"
  "${MINGW_PACKAGE_PREFIX}-pkgconf"
)
depends=(
  "${MINGW_PACKAGE_PREFIX}-libzip"
  "${MINGW_PACKAGE_PREFIX}-expat"
)
source=("https://github.com/brechtsanders/xlsxio/releases/download/${pkgver}/xlsxio-${pkgver}.tar.xz"
        0001-xlsxio-cmake-fix-install.patch)
sha256sums=('b42abf540449767832e285e79014cd2339a94613f7a63567c4118182798d55d3'
            'ad49faea2d5797ee77c0cbb0aedf565dc5a401cf0fe664a0fcad225103198673')

prepare() {
  cd "${_realname}-${pkgver}"
  patch -p1 -i "${srcdir}/0001-xlsxio-cmake-fix-install.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=" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      "${_extra_config[@]}" \
      -DBUILD_EXAMPLES=OFF \
      -DWITH_LIBZIP=ON \
      -S "${_realname}-${pkgver}" \
      -B "build-${MSYSTEM}"

  cmake --build "build-${MSYSTEM}"
}

package() {
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}"
  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE.txt" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE.txt"

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for pcfile in "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pcfile}"
  done

  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
    sed -e "s|${MINGW_PREFIX}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done
}
