#!/usr/bin/env sh

checkout="${HOME}/.local/share/rust/ripgrep"
custom=
debug=
# features='simd-accel'
features=''
target=''
target_flag=''

while [ $# -gt 0 ]; do
    case "$1" in
    --debug)
        debug=1
        shift
        ;;
    --pcre2)
        # features+=' pcre2'
        features="${features}' pcre2'"
        shift
        ;;
    --musl)
        target='aarch64-unknown-linux-gnu'
        # target='x86_64-unknown-linux-musl'
        target_flag="
        --target
        ${target}
        "
        shift
        ;;
    --help)
        echo "Usage: $(basename "$0") [--debug --pcre2 --musl]"
        exit
        ;;
    -*)
        break
        ;;
    *)
        checkout="$1"
        custom=1
        shift
        ;;
    esac
done

# export RUSTFLAGS="-C target-cpu=native"
# export RUSTFLAGS="-C target-cpu=native -C link-arg=-fuse-ld=lld"
# export RUSTFLAGS="--cfg regex_disable_auto_optimizations --cfg regex_runtime_teddy_ssse3"
if [ -n "${debug}" ]; then
  cargo build "$@" \
    --manifest-path "${checkout}/Cargo.toml" \
    --features "${features}" \
    "${target_flag}"
  if [ -z "${target}" ]; then
    bin="${checkout}/target/debug/rg"
  else
    bin="${checkout}/target/${target}/debug/rg"
  fi
else
  cargo build "$@" \
    --manifest-path "${checkout}/Cargo.toml" \
    --features "${features}" \
    --release \
    "${target_flag}"
  if [ -z "${target}" ]; then
    bin="${checkout}/target/release/rg"
  else
    bin="${checkout}/target/${target}/release/rg"
  fi
fi
if [ -z "${custom}" ]; then
  if [ -d "${HOME}/.local/share/man" ]; then
    mkdir -p "${HOME}/.local/share/man/man1"
    "${bin}" --generate man > "${HOME}/.local/share/man/man1/rg.1"
  fi
  if [ -d "${HOME}/.config/zsh/.zfunc" ]; then
    "${bin}" --generate complete-zsh > "${HOME}/.config/zsh/.zfunc/_rg"
  fi
  if [ -n "${target}" ]; then
      if [ -n "${debug}" ]; then
          cp "${bin}" "${checkout}/target/debug/rg"
      else
          cp "${bin}" "${checkout}/target/release/rg"
      fi
  fi
fi
