# Maintainer: Christoph Reiter <reiter.christoph@gmail.com>

_realname=whisper.cpp
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
epoch=1
pkgver=1.8.0
pkgrel=1
pkgdesc="Port of OpenAI's Whisper model in C/C++ (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64' 'mingw64')
url='https://github.com/ggml-org/whisper.cpp'
license=('spdx:MIT')
depends=(
  "${MINGW_PACKAGE_PREFIX}-cc-libs"
  "${MINGW_PACKAGE_PREFIX}-ggml"
  "${MINGW_PACKAGE_PREFIX}-SDL2"
)
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-cc"
  "${MINGW_PACKAGE_PREFIX}-cmake"
  "${MINGW_PACKAGE_PREFIX}-ninja"
  #"git"
)
#_commit=44fa2f647cf2a6953493b21ab83b50d5f5dbc483
#source=("git+https://github.com/ggml-org/whisper.cpp#commit=${_commit}")
source=("https://github.com/ggml-org/whisper.cpp/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz")
sha256sums=('c006a5e472ee41e7a733d0bf7326e339c8b281d3a91a1c8a35468fa0a051940f')

# pkgver() {
#   cd "${_realname}"
#   git describe --long --tags | sed 's/\([^-]*-g\)/r\1/;s/-/./g;s/^v//g'
# }

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

  LDFLAGS+=" -Wl,--export-all-symbols" \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      -DBUILD_SHARED_LIBS=ON \
      -DCMAKE_DLL_NAME_WITH_SOVERSION=ON \
      -DWHISPER_USE_SYSTEM_GGML=ON \
      -DWHISPER_CURL=ON \
      -DWHISPER_SDL2=ON \
      -DWHISPER_BUILD_EXAMPLES=ON \
      -DWHISPER_BUILD_TESTS=OFF \
      -DWHISPER_ALL_WARNINGS=OFF \
      "${extra_config[@]}" \
      ../${_realname}-${pkgver}

  cmake --build .
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" cmake --install .

  # Rename output files by prefixing them with whisper (if not already prefixed and if not DLL)
  for i in "${pkgdir}"${MINGW_PREFIX}/bin/*.{exe,py,sh}; do
    filename=$(basename "$i")
    
    if [[ -e $i && ! ("$filename" =~ ^whisper) ]]; then
      mv "${i}" "${pkgdir}${MINGW_PREFIX}/bin/whisper-${filename}"
    fi
  done

  install -Dm755 "${srcdir}/${_realname}-${pkgver}/models/download-ggml-model.sh" \
    "${pkgdir}${MINGW_PREFIX}/bin/whisper-download-ggml-model.sh"

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