#!/usr/bin/env bash

# Generated with perl module App::Spec vv0.15.0

_openqa-cli() {

    COMPREPLY=()
    local program=openqa-cli
    local cur prev words cword
    _init_completion -n : || return
    declare -a FLAGS
    declare -a OPTIONS
    declare -a MYWORDS

    local INDEX=`expr $cword - 1`
    MYWORDS=("${words[@]:1:$cword}")

    FLAGS=('--help' 'Get more information on a specific command' '-h' 'Get more information on a specific command' '--osd' 'Set target host to http://openqa.suse.de' '--o3' 'Set target host to https://openqa.opensuse.org' '--odn' 'Set target host to https://openqa.debian.net' '--links' 'Print pagination links to STDERR' '-L' 'Print pagination links to STDERR' '--pretty' 'Pretty print JSON content' '-p' 'Pretty print JSON content' '--quiet' 'Do not print error messages to STDERR' '-q' 'Do not print error messages to STDERR' '--verbose' 'Print HTTP response headers' '-v' 'Print HTTP response headers')
    OPTIONS=('--apibase' 'API base, defaults to /api/v1' '--apikey' 'API key. Use is discouraged due to risk of leaking credentials. Prefer config file or env variables.' '--apisecret' 'API secret. Use is discouraged due to risk of leaking credentials. Prefer config file or env variables.' '--host' 'Target host, defaults to http://localhost' '--name' 'Name of this client, used by openQA to identify different clients via User-Agent header, defaults to "openqa-cli" ')
    __openqa-cli_handle_options_flags

    case $INDEX in

    0)
        __comp_current_options || return
        __openqa-cli_dynamic_comp 'commands' 'api'$'\t''Issue an arbitrary request to the API'$'\n''archive'$'\t''Download assets and test results from a job'$'\n''monitor'$'\t''Monitors a set of jobs'$'\n''reservation'$'\t''Manage worker reservations'$'\n''schedule'$'\t''Schedules a set of jobs (via "isos post" creating a schedule product)'

    ;;
    *)
    # subcmds
    case ${MYWORDS[0]} in
      api)
        FLAGS+=('--form' 'Turn JSON object into form parameters' '-f' 'Turn JSON object into form parameters' '--json' 'Request content is JSON' '-j' 'Request content is JSON' '--verbose' 'Print HTTP response headers' '-v' 'Print HTTP response headers')
        OPTIONS+=('--header' 'One or more additional HTTP headers (<name:value>)' '-a' 'One or more additional HTTP headers (<name:value>)' '--data-file' 'Load content to send with request from file' '-D' 'Load content to send with request from file' '--data' 'Content to send with request' '-d' 'Content to send with request' '--param-file' 'Load content of params from files instead of from command line arguments. Multiple params may be specified by adding the option multiple times ' '--retries' 'Retry up to the specified value on some errors. Retries can also be set by the environment variable '"\\'"'OPENQA_CLI_RETRIES'"\\'"', defaults to no retry. Set '"\\'"'OPENQA_CLI_RETRY_SLEEP_TIME_S'"\\'"' to configure the sleep time between retries. ' '-r' 'Retry up to the specified value on some errors. Retries can also be set by the environment variable '"\\'"'OPENQA_CLI_RETRIES'"\\'"', defaults to no retry. Set '"\\'"'OPENQA_CLI_RETRY_SLEEP_TIME_S'"\\'"' to configure the sleep time between retries. ' '--method' 'HTTP method to use, defaults to GET' '-X' 'HTTP method to use, defaults to GET')
        __openqa-cli_handle_options_flags
        case ${MYWORDS[$INDEX-1]} in
          --apibase)
          ;;
          --apikey)
          ;;
          --apisecret)
          ;;
          --host)
          ;;
          --name)
          ;;
          --header|-a)
          ;;
          --data-file|-D)
            compopt -o filenames
            return
          ;;
          --data|-d)
          ;;
          --param-file)
          ;;
          --retries|-r)
          ;;
          --method|-X)
            _openqa-cli_compreply "GET" "HEAD" "OPTIONS" "TRACE" "PUT" "DELETE" "POST" "PATCH" "CONNECT"
            return
          ;;

        esac
        case $INDEX in
          1)
              __comp_current_options || return
          ;;
          2)
              __comp_current_options || return
          ;;


        *)
            __comp_current_options || return
        ;;
        esac
      ;;
      archive)
        FLAGS+=('--with-thumbnails' 'Download thumbnails as well' '-t' 'Download thumbnails as well')
        OPTIONS+=('--asset-size-limit' 'Asset size limit in bytes' '-l' 'Asset size limit in bytes')
        __openqa-cli_handle_options_flags
        case ${MYWORDS[$INDEX-1]} in
          --apibase)
          ;;
          --apikey)
          ;;
          --apisecret)
          ;;
          --host)
          ;;
          --name)
          ;;
          --asset-size-limit|-l)
          ;;

        esac
        case $INDEX in

        *)
            __comp_current_options || return
        ;;
        esac
      ;;
      monitor)
        FLAGS+=('--follow' 'Use the newest clone of each monitored job' '-f' 'Use the newest clone of each monitored job')
        OPTIONS+=('--poll-interval' 'Specifies the poll interval used with --monitor' '-i' 'Specifies the poll interval used with --monitor')
        __openqa-cli_handle_options_flags
        case ${MYWORDS[$INDEX-1]} in
          --apibase)
          ;;
          --apikey)
          ;;
          --apisecret)
          ;;
          --host)
          ;;
          --name)
          ;;
          --poll-interval|-i)
          ;;

        esac
        case $INDEX in

        *)
            __comp_current_options || return
        ;;
        esac
      ;;
      reservation)
        FLAGS+=('--force' 'Force reservation even if worker is already reserved' '-f' 'Force reservation even if worker is already reserved' '--release' 'Release an existing reservation' '-r' 'Release an existing reservation')
        OPTIONS+=('--comment' 'Comment describing the reason for reservation' '-c' 'Comment describing the reason for reservation' '--duration' 'Duration of the reservation (e.g. 5h, 30m, 2d, 0 for indefinite)' '-d' 'Duration of the reservation (e.g. 5h, 30m, 2d, 0 for indefinite)')
        __openqa-cli_handle_options_flags
        case ${MYWORDS[$INDEX-1]} in
          --apibase)
          ;;
          --apikey)
          ;;
          --apisecret)
          ;;
          --host)
          ;;
          --name)
          ;;
          --comment|-c)
          ;;
          --duration|-d)
          ;;

        esac
        case $INDEX in

        *)
            __comp_current_options || return
        ;;
        esac
      ;;
      schedule)
        FLAGS+=('--monitor' 'Wait until all jobs are done/cancelled and return non-zero exit code if at least on job has not passed/softfailed ' '-m' 'Wait until all jobs are done/cancelled and return non-zero exit code if at least on job has not passed/softfailed ' '--follow' 'Use the newest clone of each monitored job' '-f' 'Use the newest clone of each monitored job')
        OPTIONS+=('--param-file' 'Load content of params from files instead of from command line arguments. Multiple params may be specified by adding the option multiple times ' '--poll-interval' 'Specifies the poll interval used with --monitor' '-i' 'Specifies the poll interval used with --monitor')
        __openqa-cli_handle_options_flags
        case ${MYWORDS[$INDEX-1]} in
          --apibase)
          ;;
          --apikey)
          ;;
          --apisecret)
          ;;
          --host)
          ;;
          --name)
          ;;
          --param-file)
          ;;
          --poll-interval|-i)
          ;;

        esac
        case $INDEX in

        *)
            __comp_current_options || return
        ;;
        esac
      ;;
    esac

    ;;
    esac

}

_openqa-cli_compreply() {
    local prefix=""
    cur="$(printf '%q' "$cur")"
    IFS=$'\n' COMPREPLY=($(compgen -P "$prefix" -W "$*" -- "$cur"))
    __ltrim_colon_completions "$prefix$cur"

    # http://stackoverflow.com/questions/7267185/bash-autocompletion-add-description-for-possible-completions
    if [[ ${#COMPREPLY[*]} -eq 1 ]]; then # Only one completion
        COMPREPLY=( "${COMPREPLY[0]%% -- *}" ) # Remove ' -- ' and everything after
        COMPREPLY=( "${COMPREPLY[0]%%+( )}" ) # Remove trailing spaces
    fi
}


__openqa-cli_dynamic_comp() {
    local argname="$1"
    local arg="$2"
    local name desc cols desclength formatted
    local comp=()
    local max=0

    while read -r line; do
        name="$line"
        desc="$line"
        name="${name%$'\t'*}"
        if [[ "${#name}" -gt "$max" ]]; then
            max="${#name}"
        fi
    done <<< "$arg"

    while read -r line; do
        name="$line"
        desc="$line"
        name="${name%$'\t'*}"
        desc="${desc/*$'\t'}"
        if [[ -n "$desc" && "$desc" != "$name" ]]; then
            # TODO portable?
            cols=`tput cols`
            [[ -z $cols ]] && cols=80
            desclength=`expr $cols - 4 - $max`
            formatted=`printf "%-*s -- %-*s" "$max" "$name" "$desclength" "$desc"`
            comp+=("$formatted")
        else
            comp+=("'$name'")
        fi
    done <<< "$arg"
    _openqa-cli_compreply ${comp[@]}
}

function __openqa-cli_handle_options() {
    local i j
    declare -a copy
    local last="${MYWORDS[$INDEX]}"
    local max=`expr ${#MYWORDS[@]} - 1`
    for ((i=0; i<$max; i++))
    do
        local word="${MYWORDS[$i]}"
        local found=
        for ((j=0; j<${#OPTIONS[@]}; j+=2))
        do
            local option="${OPTIONS[$j]}"
            if [[ "$word" == "$option" ]]; then
                found=1
                i=`expr $i + 1`
                break
            fi
        done
        if [[ -n $found && $i -lt $max ]]; then
            INDEX=`expr $INDEX - 2`
        else
            copy+=("$word")
        fi
    done
    MYWORDS=("${copy[@]}" "$last")
}

function __openqa-cli_handle_flags() {
    local i j
    declare -a copy
    local last="${MYWORDS[$INDEX]}"
    local max=`expr ${#MYWORDS[@]} - 1`
    for ((i=0; i<$max; i++))
    do
        local word="${MYWORDS[$i]}"
        local found=
        for ((j=0; j<${#FLAGS[@]}; j+=2))
        do
            local flag="${FLAGS[$j]}"
            if [[ "$word" == "$flag" ]]; then
                found=1
                break
            fi
        done
        if [[ -n $found ]]; then
            INDEX=`expr $INDEX - 1`
        else
            copy+=("$word")
        fi
    done
    MYWORDS=("${copy[@]}" "$last")
}

__openqa-cli_handle_options_flags() {
    __openqa-cli_handle_options
    __openqa-cli_handle_flags
}

__comp_current_options() {
    local always="$1"
    if [[ -n $always || ${MYWORDS[$INDEX]} =~ ^- ]]; then

      local options_spec=''
      local j=

      for ((j=0; j<${#FLAGS[@]}; j+=2))
      do
          local name="${FLAGS[$j]}"
          local desc="${FLAGS[$j+1]}"
          options_spec+="$name"$'\t'"$desc"$'\n'
      done

      for ((j=0; j<${#OPTIONS[@]}; j+=2))
      do
          local name="${OPTIONS[$j]}"
          local desc="${OPTIONS[$j+1]}"
          options_spec+="$name"$'\t'"$desc"$'\n'
      done
      __openqa-cli_dynamic_comp 'options' "$options_spec"

      return 1
    else
      return 0
    fi
}


complete -o default -F _openqa-cli openqa-cli

