_rci_compadd() {
 [ -z "$1" ] && shift
 COMPREPLY=( $( compgen -W '$*' -- "$cur" ))
}

_rci_jobs() {
  if [ "$RCI_AC_CONFIG" ]; then
    rci --config "$RCI_AC_CONFIG" job list --short
  else
    rci job list --short
  fi
}

_rci_job() {
  case ${words[2]} in
    run)
      case $CURRENT in
        3)
          _rci_compadd $(_rci_jobs) "" -f
          ;;
        4)
          case $prev in
            -f)
              _rci_compadd $(_rci_jobs)
              ;;
            *)
              _rci_compadd "" -f
              ;;
          esac
          ;;
      esac
      ;;
    export)
      case $CURRENT in
        3)
          _rci_compadd $(_rci_jobs) "" -y --full
          ;;
        4)
          case $prev in
            -y|--full)
              _rci_compadd $(_rci_jobs)
              ;;
            *)
              _rci_compadd "" -y --full
              ;;
          esac
          ;;
      esac
      ;;
    terminate|kill|purge|deploy|edit|delete)
      _rci_compadd $(_rci_jobs)
      ;;
    *)
      if [ $CURRENT -eq 2 ]; then
        _rci_compadd list run terminate kill purge deploy edit export delete
      fi
      ;;
  esac
}

_rci_task() {
  case ${words[2]} in
    list)
      case $prev in
        -s|-e|--start|--end)
          return
          ;;
        --status)
          _rci_compadd all finished active
          return
          ;;
        -j|--job)
          _rci_compadd $(_rci_jobs)
          return
          ;;
        --status)
          _rci_compadd all active finished
          return
          ;;
      esac
      _rci_compadd "" -j --job -s --start -e --end --status
      ;;
    *)
      if [ $CURRENT -eq 2 ]; then
        _rci_compadd list info delete
      fi
      ;;
  esac
}

_rci() {
  _init_completion || return
  CURRENT=$cword
  case $prev in
    --color)
      _rci_compadd always never
      return
      ;;
    --config)
      COMPREPLY=( $(compgen -f -- "$cur"; compgen -d -S / -- "$cur") )
      return
      ;;
    --timeout)
      return
      ;;
  esac
  RCI_AC_CONFIG=
  while true; do
    case ${words[1]} in
      --json)
        words=("${words[@]:1}")
        CURRENT=$(( CURRENT-1 ))
        ;;
      --color|--timeout|configure)
        words=("${words[@]:2}")
        CURRENT=$(( CURRENT-2 ))
        ;;
      --config)
        RCI_AC_CONFIG=${words[2]}
        words=("${words[@]:2}")
        CURRENT=$(( CURRENT-2 ))
        ;;
      *)
        break
        ;;
    esac
  done
  if [ $CURRENT -eq 1 ]; then
    _rci_compadd job task x configure --color --config --timeout --json
  else
    case ${words[1]} in
      job|task|x)
        _rci_${words[1]}
        ;;
    esac
  fi
}

complete -F _rci rci
