#! /bin/bash
# vim: shiftwidth=2 tabstop=2 expandtab

[[ $( id -u ) -ne 0 ]] && return

_authentic2_manage_subcommands_cache_file=/tmp/.authentic2-manage_$(dpkg -l |grep authentic2|awk '{print $2 " " $3}'|md5sum|awk '{print $1}')_completion.cache

_array_filter() {
  local VALUES=()
  local x=0
  for v in "$@"; do
    if [ "$v" == "--" ]; then
      x=1
    elif [ $x -eq 0 ]; then
      VALUES+=( "$v" )
    else
      VALUES=( "${VALUES[@]#$v}" )
    fi
  done
  printf %s "${VALUES}" "${VALUES[@]/#/$IFS}"
}

_authentic2_manage_list_subcommands() {
  CMDS=""
  [[ -e $_authentic2_manage_subcommands_cache_file ]] && \
    CMDS="$(cat $_authentic2_manage_subcommands_cache_file 2>/dev/null)"
  [[ -z "$CMDS" ]] && \
    CMDS="$(
      authentic2-manage 2> /dev/null |grep -E '^    '|tr -d ' '|tr '\n' ' ' | \
        tee $_authentic2_manage_subcommands_cache_file 2>/dev/null
    )"
	echo "$CMDS"
}

_authentic2_manage_completion() {
	local cur
	COMPREPLY=()
	cur=${COMP_WORDS[COMP_CWORD]}

	# Set default options
	OPTS=(-h --help help -v --settings --pythonpath --traceback --no-color --force-color --skip-checks)

	idx=1
	subcommand=""
	while [ $idx -le ${#COMP_WORDS[@]} ]
	do
		OPT=${COMP_WORDS[$idx]}
		case $OPT in
			-h|--help)
        OPTS=( $(_array_filter ${OPTS[@]} -- -h --help) )
        [[ $idx -eq $COMP_CWORD ]] && { COMPREPLY=("$OPT"); return; }
        ;;
			help)
				OPTS=( $(_array_filter ${OPTS[@]} -- -h --help help) )
				[[ $idx -eq $COMP_CWORD ]] && { COMPREPLY=("$OPT"); return; }
				((idx++))
				if [[ $idx -eq $COMP_CWORD ]]; then
          COMPREPLY=( $( compgen -W "$(_authentic2_manage_list_subcommands)" -- $cur ) )
          return
        fi
				;;
			--settings|--pythonpath)
				OPTS=( $(_array_filter ${OPTS[@]} -- $OPT) )
				[[ $idx -eq $COMP_CWORD ]] && { COMPREPLY=( $OPT ); return; }
				((idx++))
				[[ $idx -eq $COMP_CWORD ]] && { _filedir; return; }
        ;;
			--traceback|--no-color|--force-color|--skip-checks)
				OPTS=( $(_array_filter ${OPTS[@]} -- $OPT) )
				[[ $idx -eq $COMP_CWORD ]] && { COMPREPLY=("$OPT"); return; }
        ;;
      -v)
				OPTS=( $(_array_filter ${OPTS[@]} -- $OPT) )
				[[ $idx -eq $COMP_CWORD ]] && { COMPREPLY=( $OPT ); return; }
				((idx++))
				if [[ $idx -eq $COMP_CWORD ]]; then
          COMPREPLY=( $( compgen -W "0 1 2 3" -- ${COMP_WORDS[COMP_CWORD]} ) )
          return
        fi
        ;;
      *)
        if [[ -z "$subcommand" ]]; then
          [ $idx -ne $COMP_CWORD ] && subcommand="$OPT"
        fi
        ;;
		esac
		((idx++))
	done

	[[ -z "$subcommand" ]] && OPTS=( "${OPTS[@]}" "$(_authentic2_manage_list_subcommands)" )
  OPTS="${OPTS[@]}"
	COMPREPLY=( $( compgen -W "$OPTS" -- ${COMP_WORDS[COMP_CWORD]} ) )
}
complete -F _authentic2_manage_completion -o default authentic2-manage
