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

_realname=librime
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=1.14.0
pkgrel=1
pkgdesc="Rime Input Method Engine Library (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://rime.im/'
msys2_repository_url="https://github.com/rime/librime"
license=('spdx:BSD-3-Clause')
depends=("${MINGW_PACKAGE_PREFIX}-cc-libs"
         "${MINGW_PACKAGE_PREFIX}-leveldb"
         "${MINGW_PACKAGE_PREFIX}-opencc"
         "${MINGW_PACKAGE_PREFIX}-yaml-cpp"
         "${MINGW_PACKAGE_PREFIX}-glog")
optdepends=("${MINGW_PACKAGE_PREFIX}-rime-data: Rime schema repository from plum")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-boost"
             "${MINGW_PACKAGE_PREFIX}-marisa")
checkdepends=("${MINGW_PACKAGE_PREFIX}-gtest")
source=("https://github.com/rime/librime/archive/${pkgver}/${_realname}-${pkgver}.tar.gz"
        "001-fix-librime-path.patch"
        "002-librime-fix-llvm-rc.patch")
sha256sums=('b2b29c3551eec6b45af1ba8fd3fcffb99e2b7451aa974c1c9ce107e69ce3ea68'
            '8fe90184aadd788f1ec87d2b009016f9c1c6e4ecdaf92d7e3d4c2255c36a1ccb'
            'fcddd5b4f817ba4bda81cd428ff8b6962ed8e4124722e1de99875697e354c355')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${_realname}-${pkgver}"
  apply_patch_with_msg \
    001-fix-librime-path.patch \
    002-librime-fix-llvm-rc.patch
}

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

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  export CXXFLAGS="$CXXFLAGS -DNDEBUG -DGLOG_USE_GLOG_EXPORT -DGLOG_USE_GFLAGS"
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe -Wno-dev \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
    "${_extra_config[@]}" \
    -DBUILD_TEST=OFF \
    "../${_realname}-${pkgver}"

  ${MINGW_PREFIX}/bin/cmake --build .
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  ${MINGW_PREFIX}/bin/cmake -DBUILD_TEST=ON ../${_realname}-${pkgver}
  ${MINGW_PREFIX}/bin/cmake --build .

  PATH=${PATH}:"${srcdir}/build-${MSYSTEM}/bin" ${MINGW_PREFIX}/bin/ctest .
}

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