#!/hint/zsh
emulate -LR zsh -o extended_glob

local zsh_version=${1:-${FZF_TAB_ZSH_SRC_VERSION:-$ZSH_VERSION}}

# macos check
local ret bundle nproc
if [[ $OSTYPE == darwin* ]]; then
  [[ -n ${module_path[1]}/**/*.bundle(#qN) ]] && bundle=true
  nproc=$(sysctl -n hw.logicalcpu)
else
  nproc=$(nproc)
fi

pushd -q $FZF_TAB_HOME/modules

# clone zsh source code if not exists
if [[ ! -d ./zsh/$zsh_version ]]; then
  git clone --depth=1 --branch zsh-$zsh_version https://github.com/zsh-users/zsh ./zsh/$zsh_version
  ln -s $PWD/src/fzftab.c   ./zsh/$zsh_version/Src/Modules/
  ln -s $PWD/src/fzftab.mdd ./zsh/$zsh_version/Src/Modules/
fi

# build zsh
cd -q ./zsh/$zsh_version
if [[ ! -f ./configure ]]; then
  ./Util/preconfig
fi
if [[ ! -f ./Makefile ]]; then
  ./configure --disable-gdbm --disable-pcre --without-tcsetpgrp --prefix=/tmp/zsh-fzf-tab-module ${bundle:+DL_EXT=bundle}
fi
make -j$nproc
ret=$?

if (( $ret != 0 )); then
  print -P -u2 "%F{red}%BThe module building has failed. See the output above for details.%f%b"
  return $ret
fi

# we only need aloxaf/fzftab.so
mv ./Src/Modules/fzftab.(so|bundle) $FZF_TAB_HOME/modules/Src/aloxaf/

popd -q

print -P "%F{green}%BThe module has been built successfully. Please restart zsh to apply it.%f%b"
