#!/usr/bin/env bash

set -eu

: "${VIM_SOURCE:="${HOME}"/.vim-source}"

log() {
  printf '%s: ' "$0"
  printf '%s\n' "$@"
} >&2

install_deps() {
  if ! command -v brew >/dev/null 2>/dev/null; then
    log 'missing brew'
    return 1
  fi
  set -- deps
  readonly deps
  deps=$(brew deps --1 --include-build --include-optional vim | grep -v 'lua\|perl\|ruby')
  brew install "${deps}"
}

clone_vim() {
  if ! [ -d "${VIM_SOURCE}" ]; then
    git clone --depth=1 --no-tags https://github.com/vim/vim "${VIM_SOURCE}"
  else
    git -C "${VIM_SOURCE}" fetch --depth=1
    git -C "${VIM_SOURCE}" reset --hard HEAD@'{upstream}'
  fi
}

build_and_install_vim() (
  # future ref: https://github.com/Homebrew/homebrew-core/commit/174f85e0004c4aafc92714558c2b37c57e8ff925
  cd "${VIM_SOURCE}" || return
  unset SDKROOT PYTHONPATH
  # local python python_path
  python=$(brew deps --1 --include-build --include-optional vim | grep python | head -n 1)
  python_path="$(brew --prefix "${python}")/bin"
  PATH="${python_path}:${PATH}"
  configure_args='
    --with-tlib=ncurses
    --with-compiledby=benknoble
    --enable-cscope
    --enable-terminal
    --enable-python3interp
    --enable-gui=no
    --without-x
  '
  time ./configure "${configure_args}"
  # shellcheck disable=SC2312
  time make -j "$(nproc)"
  time TERMINFO=~/.local/share/terminfo make test
  # shellcheck disable=SC2312
  time make install STRIP="$(command -v true)"
)

main() {
  install_deps
  clone_vim
  time build_and_install_vim
}

main
