# Maintainer: aur.chaotic.cx

: ${_build_clang:=true}

: ${_build_pgo:=true}

_pkgname=stockfish
pkgname="$_pkgname"
pkgver=20260630-60888387
pkgrel=1
pkgdesc="A strong UCI chess engine"
url="https://github.com/official-stockfish/Stockfish"
license=('GPL-3.0-only')
arch=('x86_64')

depends=(
  'gcc-libs'
)
makedepends=(
  'git'
)
optdepends=(
  'polyglot-winboard: xboard support'
)

if [[ "${_build_clang::1}" == "t" ]]; then
  makedepends+=(
    'clang'
    'lld'
    'llvm'
  )
fi

_pkgsrc="Stockfish-sf_$pkgver"
source=("$_pkgname-$pkgver.zip"::"$url/archive/sf_$pkgver.zip")
sha256sums=('SKIP')

prepare() {
  # download nnue files
  local _nnue_big=$(grep -Em1 'define EvalFileDefaultNameBig' "$_pkgsrc/src/evaluate.h" | sed -E 's&^.*"(\S+)".*$&\1&')
  local _nnue_small=$(grep -Em1 'define EvalFileDefaultNameBig' "$_pkgsrc/src/evaluate.h" | sed -E 's&^.*"(\S+)".*$&\1&')

  curl -qgC - -o "$_nnue_big" "https://tests.stockfishchess.org/api/nn/${_nnue_big}"
  curl -qgC - -o "$_nnue_small" "https://tests.stockfishchess.org/api/nn/${_nnue_small}"

  ln -sf "$srcdir/$_nnue_big" "$_pkgsrc/src/"
  ln -sf "$srcdir/$_nnue_small" "$_pkgsrc/src/"
}

build() {
  # aur/stockfish, aur/stockfish-git, and upstream stockfish build scripts
  # detect and force-enable cpu features, ignoring user CFLAGS and CXXFLAGS,
  # producing binaries that are unusable on some computers.
  #
  # The following replicates `make profile-build` without cpu-detection.
  cd "$_pkgsrc/src"

  if [[ "${_build_clang::1}" == "t" ]]; then
    local _make=(make COMP=clang 'ARCH=" "')
  else
    local _make=(make COMP=gcc 'ARCH=" "')
  fi

  # prepare nnue
  "${_make[@]}" net

  if [[ "${_build_pgo::1}" == "t" ]]; then
    if [[ "${_build_clang::1}" == "t" ]]; then
      local _pgo_gen_options=(
        EXTRACXXFLAGS="-fprofile-generate"
        EXTRALDFLAGS=""
      )
      local _pgo_use_options=(
        EXTRACXXFLAGS="-fprofile-use=$pkgname.prof"
        EXTRALDFLAGS=""
      )
    else
      local _pgo_gen_options=(
        EXTRACXXFLAGS="-fprofile-generate=profdir"
        EXTRALDFLAGS="-lgcov"
      )
      local _pgo_use_options=(
        EXTRACXXFLAGS="-fprofile-use=profdir -fno-peel-loops -fno-tracer"
        EXTRALDFLAGS="-lgcov"
      )
    fi

    printf "\nStep 1. Building instrumented executable ...\n"
    mkdir -p profdir
    "${_make[@]}" "${_pgo_gen_options[@]}" all

    printf "\nStep 2. Running benchmark for pgo-build ...\n"
    ./stockfish bench > PGOBENCH.out

    if [[ "${_build_clang::1}" == "t" ]]; then
      llvm-profdata merge -output=$pkgname.prof *.profraw
    fi

    printf "\nStep 3. Building optimized executable ...\n"

    "${_make[@]}" objclean
    "${_make[@]}" "${_pgo_use_options[@]}" all

    #printf "\nStep 4. Deleting profile data ...\n"
    #"${_make[@]}" profileclean
  else
    printf "\nStep 1. Building standard executable ...\n"
    "${_make[@]}" all
  fi
}

package() {
  cd "$_pkgsrc/src"
  make PREFIX="$pkgdir/usr" install
}
