#!/usr/bin/env sh

set -e
set -ux

bashuserdest="${HOME%/}"'/.local/share/bash-completion'
zshdest="${HOME%/}"'/.config/zsh/completions'
zfuncdest="${HOME%/}"'/.config/zsh/.zfunc'

run() {
  echo '$' "$@"
  "$@"
}

make_dir() {
  run mkdir -p "$1"
}

# cht.sh
# update_chtsh() {
#   curl -fsSL "https://cheat.sh/:bash_completion" -o "${bashuserdest}"/cht 2>/dev/null
#   curl -fsSL "https://cheat.sh/:zsh" -o "${zshdest}"/_cht 2>/dev/null
# }
# update_chtsh 2>/dev/null

# cargo/rustup
if command -v rustup >/dev/null 2>&1; then
  rustup completions zsh >|"${zfuncdest}"/_rustup
  rustup completions zsh cargo >|"${zfuncdest}"/_cargo
  rustup completions bash >|"${bashuserdest}"/rustup
  rustup completions bash cargo >|"${bashuserdest}"/cargo
fi

# chafa
if command -v chafa >/dev/null 2>&1; then
  chafaurl=https://raw.githubusercontent.com/hpjansson/chafa/refs/heads/master/tools/completions
  curl -fsSL "${chafaurl}"/zsh-completion.zsh -o "${zshdest}"/_chafa
fi

# fd
# https://raw.githubusercontent.com/sharkdp/fd/refs/heads/master/contrib/completion/_fd
if command -v fd >/dev/null 2>&1; then
  fdurl=https://raw.githubusercontent.com/sharkdp/fd/refs/heads/master/contrib/completion
  curl -fsSL "${fdurl}"/_fd -o "${zfuncdest}"/_fd
fi

# # git
# if command -v git >/dev/null 2>&1; then
#   giturl=https://raw.githubusercontent.com/git/git/master/contrib/completion
#   curl -fsSL "${giturl}"/git-completion.zsh -o "${zshdest}"/_git
# fi

# # newsboat
# if command -v newsboat >/dev/null 2>&1; then
#   nburl="https://raw.githubusercontent.com/newsboat/newsboat/refs/heads/master/contrib/completions"
#   curl -fsSL "${nburl}"/_newsboat -o "${zshdest}"/_newsboat
# fi

# ov
if command -v ov >/dev/null 2>&1; then
  ov --completion zsh >|"${zfuncdest}"/_ov
  ov --completion bash >|"${bashuserdest}"/ov
fi

# qgrep
if command -v qgrep >/dev/null 2>&1; then
  qgrepurl=https://raw.githubusercontent.com/zeux/qgrep/refs/heads/master/shell-completion/bash
  curl -sSfL "${qgrepurl}"/qgrep -o "${bashuserdest}"/qgrep
fi

# pipx
if command -v pipx >/dev/null 2>&1; then
  register-python-argcomplete pipx >|"${zfuncdest}"/_pipx
fi

# ripgrep
if command -v rg >/dev/null 2>&1; then
  rgurl=https://raw.githubusercontent.com/BurntSushi/dotfiles/refs/heads/master/.zsh-complete
  curl -sSfL "${rgurl}"/_rg -o "${zfuncdest}"/_rg
fi

# watchexec
if command -v watchexec >/dev/null 2>&1; then
  watchexec --completions bash >|"${bashuserdest}"/watchexec
  watchexec --completions zsh >|"${zshdest}"/_watchexec
fi

{
  set +ux
} 2>/dev/null
