#
# Keyringer bash completion
#

if [[ -n ${ZSH_VERSION-} ]]; then
  autoload -U +X bashcompinit && bashcompinit
fi

# Completion for git subcommand
_keyringer_git_complete() {
  local git_completion=""

  if [ -e "/etc/bash_completion.d/git" ]; then
    git_completion="/etc/bash_completion.d/git"
  elif [ -e "/usr/share/bash-completion/completions/git" ]; then
    git_completion="/usr/share/bash-completion/completions/git"
  fi

  if [ ! -z "$git_completion" ]; then
    (
      source $git_completion
      cd $path
      COMP_WORDS=(git $*)
      COMP_CWORD=$((${#COMP_WORDS[*]} - 1))

      if [ "$COMP_CWORD" == "0" ]; then
        COMP_CWORD=1
      fi

      _git

      LAST=${COMP_WORDS[COMP_CWORD]}
      REPLY=${COMPREPLY[@]}

      if [ "$REPLY" == "$LAST" ]; then
        return
      fi

      echo ${COMPREPLY[@]}
    )
  fi
}

# Path completion
function _keyringer_path_complete() {
  # Thanks http://unix.stackexchange.com/questions/55520/create-bash-completion-script-to-autocomplete-paths-after-is-equal-sign
  cur=${1//\\ / }
  [[ ${cur} == "~"* ]] && cur=${cur/\~/$HOME}

  echo ${cur}
}

# Main completion
_keyringer() {
  # Standard stuff
  local cur prev command config path keyrings instances instance opts
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  prev="${COMP_WORDS[COMP_CWORD-1]}"
  command="${COMP_WORDS[2]}"

  # Initial options
  config="$HOME/.keyringer"

  # Check if we have initial configuration
  if [ ! -d "$config" ]; then
    return
  fi

  # Process config
  keyrings="`ls --color=never $config | sed -e '/^config$/d' | xargs`"

  # Available instances
  instances="`echo $keyrings | sed -e 's/ /$\\\|^/g' -e 's/^/^/' -e 's/$/$/'`"

  # The current instance
  instance="${COMP_WORDS[1]}"
  path="`grep -e "^$instance=" "$config/config" | tail -n 1 | cut -d = -f 2 | sed -e 's/"//g' -e "s/'//g" | sed -e 's/ *#.*$//'`"

  # Command completions
  if [ "${#COMP_WORDS[@]}" == "2" ]; then
    opts="$keyrings"
  elif [ "${#COMP_WORDS[@]}" == "3" ] && echo "${prev}" | grep -qe "$instances"; then
    opts="`export KEYRINGER_CHECK_RECIPIENTS=false && export KEYRINGER_CHECK_VERSION=false && keyringer $instance commands`"
  elif [ "${#COMP_WORDS[@]}" == "3" ]; then
    opts="init"
  elif [ "${#COMP_WORDS[@]}" == "4" ]; then
    case "${prev}" in
      options|preferences)
        opts="ls edit add"
        ;;
      recipients)
        opts="ls edit"
        ;;
      ls|tree|mkdir|encrypt|encrypt-batch|pwgen|decrypt|edit|append|append-batch|del|rm|recrypt|open|clip|xclip|sclip|search|ssearch|find|mv|cp)
        cur="`echo ${cur} | sed -e "s|^/*||"`" # avoid leading slash
        opts="$(bash -c "set -f && export KEYRINGER_CHECK_RECIPIENTS=false && export KEYRINGER_CHECK_VERSION=false && keyringer $instance ls -p -d ${cur}*" 2> /dev/null)"
        ;;
      genkeys|genpair)
        opts="gpg ssh x509 x509-self ssl ssl-self"
        ;;
      git)
        opts="$(_keyringer_git_complete ${cur})"
        ;;
      init)
        cur="$(_keyringer_path_complete ${cur})"
        opts="`compgen -o default "${cur}"`"
        ;;
      *)
        ;;
    esac
  elif [ "${#COMP_WORDS[@]}" == "5" ]; then
    case "${command}" in
      mv|cp)
        cur="`echo ${cur} | sed -e "s|^/*||"`" # avoid leading slash
        opts="$(bash -c "set -f && export KEYRINGER_CHECK_RECIPIENTS=false && export KEYRINGER_CHECK_VERSION=false && keyringer $instance ls -p -d ${cur}*" 2> /dev/null)"
        ;;
      recipients)
        cur="`echo ${cur} | sed -e "s|^/*||"`" # avoid leading slash
        opts="$(cd $path/config/recipients && ls --color=never -p ${cur}* 2> /dev/null)"
        ;;
      genkeys|genpair)
        cur="`echo ${cur} | sed -e "s|^/*||"`" # avoid leading slash
        opts="$(bash -c "set -f && export KEYRINGER_CHECK_RECIPIENTS=false && export KEYRINGER_CHECK_VERSION=false && keyringer $instance ls -p -d ${cur}*" 2> /dev/null)"
        ;;
      git)
        # TODO
        opts="$(_keyringer_git_complete ${prev} ${cur})"
        ;;
      encrypt|encrypt-batch|pwgen)
        cur="$(_keyringer_path_complete ${cur})"
        opts="`compgen -o default "${cur}"`"
        ;;
      *)
        ;;
    esac
  elif [ "${command}" == "git" ]; then
    # TODO
    opts="$(_keyringer_git_complete ${COMP_WORDS[@]:3})"
  fi

  # Avoid annoying bell and extra tab
  if [ -z "$ZSH_VERSION" ]; then
    bind 'set show-all-if-ambiguous on'
  fi

  # Return the available options
  COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )

  if [ -z "$ZSH_VERSION" ]; then
    [[ $COMPREPLY == */ ]] && compopt -o nospace
  fi

  return 0
}

complete -F _keyringer keyringer
