# bash completions for studip-router (`studip`)
# Install: studip completion bash > ~/.local/share/bash-completion/completions/studip
#          (or `source` it from ~/.bashrc)

# Course folders often contain spaces ("Mathe I"): offer them escaped.
_studip_courses() {
  local IFS=$'\n' course
  for course in $(command studip _complete courses 2>/dev/null | cut -f1); do
    [[ "$course" == "$1"* ]] && printf '%q\n' "$course"
  done
}

_studip() {
  local cur prev cmd
  cur="${COMP_WORDS[COMP_CWORD]}"
  prev="${COMP_WORDS[COMP_CWORD-1]}"
  local commands="init open courses sync status reorganize undo history news merge doctor tui completion auth config rules schedule ignore dates pdf-password"

  # the first word that is a command
  local i
  for ((i = 1; i < COMP_CWORD; i++)); do
    case "${COMP_WORDS[i]}" in
      -p|--profile) ((i++)) ;;
      -*) ;;
      *) cmd="${COMP_WORDS[i]}"; break ;;
    esac
  done

  case "$prev" in
    -p|--profile)
      COMPREPLY=($(compgen -W "$(command studip _complete profiles 2>/dev/null)" -- "$cur"))
      return ;;
    --course)
      local IFS=$'\n'
      COMPREPLY=($(_studip_courses "$cur"))
      return ;;
    --ics)
      COMPREPLY=($(compgen -f -- "$cur"))
      return ;;
    -s|--semester)
      COMPREPLY=($(compgen -W "current all" -- "$cur"))
      return ;;
  esac

  if [[ "$cmd" == open ]]; then
    local IFS=$'\n'
    COMPREPLY=($(_studip_courses "$cur"))
    return
  fi

  local words
  case "$cmd" in
    "") words="$commands -p --profile --json --version" ;;
    sync) words="--course -s --semester -n --dry-run --include-large -v --verbose -q --quiet --notify" ;;
    reorganize) words="--course -n --dry-run -y --yes" ;;
    undo) words="-y --yes" ;;
    history) words="-l --limit" ;;
    completion) words="zsh bash fish" ;;
    news) words="--course --all --keep-unread" ;;
    merge) words="--course --force" ;;
    dates) words="--days --offline --ics" ;;
    status) words="--offline" ;;
    doctor) words="--offline --test-notification" ;;
    courses) words="-s --semester" ;;
    init) words="--force" ;;
    auth) words="login status logout" ;;
    config) words="path validate edit set remove-course" ;;
    schedule) words="install uninstall status run-now" ;;
    ignore) words="add list remove" ;;
    pdf-password) words="set list remove" ;;
    rules) words="list test suggest" ;;
  esac
  COMPREPLY=($(compgen -W "$words" -- "$cur"))
}

complete -F _studip studip
