# Maintainer: Feng Shu <tumashu@163.com>

_realname=opencc
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.1.9
pkgrel=1
pkgdesc="Library for Open Chinese Convert (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/BYVoid/OpenCC"
license=('spdx:Apache-2.0')
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-marisa"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-python"
             "${MINGW_PACKAGE_PREFIX}-rapidjson")
source=("https://github.com/BYVoid/OpenCC/archive/ver.${pkgver/${_realname}-${pkgver}}.tar.gz")
sha256sums=('ad4bcd8d87219a240a236d4a55c9decd2132a9436697d2882ead85c8939b0a99')

prepare() {
   mv "${srcdir}/OpenCC-ver.${pkgver}" "${_realname}-${pkgver}"
   cd "${_realname}-${pkgver}"
}

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=" \
  "${MINGW_PREFIX}"/bin/cmake.exe \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DENABLE_GTEST=OFF \
    -DBUILD_SHARED_LIBS=OFF \
    -DPYTHON_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe \
    -DUSE_SYSTEM_MARISA=ON \
    -DUSE_SYSTEM_RAPIDJSON=ON \
    -S "${_realname}-${pkgver}" \
    -B "build-${MSYSTEM}-static"

  "${MINGW_PREFIX}"/bin/cmake.exe --build "build-${MSYSTEM}-static"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  "${MINGW_PREFIX}"/bin/cmake.exe \
    -GNinja \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    "${_extra_config[@]}" \
    -DENABLE_GTEST=OFF \
    -DBUILD_SHARED_LIBS=ON \
    -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
    -DPYTHON_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe \
    -DUSE_SYSTEM_MARISA=ON \
    -DUSE_SYSTEM_RAPIDJSON=ON \
    -S "${_realname}-${pkgver}" \
    -B "build-${MSYSTEM}-shared"

  "${MINGW_PREFIX}"/bin/cmake.exe --build "build-${MSYSTEM}-shared"
}

package() {
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}-static"
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}-shared"

  # fix cmake and pkg-config files
  find "${pkgdir}${MINGW_PREFIX}/lib/cmake" -type f -name '*.cmake' \
      -exec sed -i -e "s|${MINGW_PREFIX}|\$\{PACKAGE_PREFIX_DIR\}|g" {} \;
  sed -e "s|${MINGW_PREFIX}/|\$\{prefix\}/|g" -i "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/opencc.pc

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