#!/usr/bin/bash -efu

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See LICENSE for more details.
#
# Copyright: Red Hat Inc. 2019, 2023
# Author: Andrei Stepanov <astepano@redhat.com>

shopt -s extglob

# Source `mtps-setup' from $PATH
if command -v "mtps-setup" >/dev/null; then source "mtps-setup"; fi
# If previous fails source `mtps-setup` from this script dir
if [ -z "${YUMDNFCMD:-}" ]; then source "$(dirname "${BASH_SOURCE[0]}")/mtps-setup" || ( echo "Cannot source mtps-setup" >&2; exit 91 ); fi

tagged2tasks() {
    local xml="$1" && shift
    local tasks
    tasks="$(xml_get_value "$xml" '//member[name="task_id"]//value/int/text()')"
    debug "Tag tasks:\n${tasks}\n---"
    echo "$tasks"
}

tagged2nvrs() {
    local xml="$1" && shift
    local nvrs
    nvrs="$(xml_get_value "$xml" '//member[name="nvr"]//value/string/text()')"
    debug "Tag tasks:\n${nvrs}\n---"
    echo "$nvrs"
}

tag_info2tag_id() {
    local xml="$1" && shift
    local task=
    tag_id="$(xml_get_value "$xml" '//member[name="id"]/value/int/text()' | head -1)"
    debug "Tag name: $tag_id"
    echo "$tag_id"
}

send_query() {
    local query="$1" && shift
    local answer
    answer="$(curl --silent -k --data "$query" "$BREWHUB")"
    debug "Brew answer:\n${answer}"
    echo "$answer"
}

# Use:
#
#     'koji list-api' to get a list of available XMLRPC.
#     'brew --debug-xmlrpc' to get XML
#

brew_get_tag() {
    # tag may be either
    # a string (the tag name) or an int (the tag ID)
    local tag="$1" && shift
    local re='^[0-9]+$'
    [[ $tag =~ $re ]] && tag="<int>$tag</int>"
    local query="$(cat << EOF
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>getTag</methodName>
  <params>
    <param>
      <value>
        <string>$tag</string>
      </value>
    </param>
  </params>
</methodCall>
EOF
    )"
    debug "Brew query for getTag: ${query:0:200}...(truncated)"
    send_query "$query"
}


brew_list_tagged() {
    # tag: tag name or ID number
    local tag="$1" && shift
    local re='^[0-9]+$'
    [[ $tag =~ $re ]] && tag="<int>$tag</int>"
    local query="$(cat << EOF
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>listTagged</methodName>
  <params>
    <param>
      <value>
        <string>$tag</string>
      </value>
    </param>
  </params>
</methodCall>
EOF
    )"
    debug "Brew query for listTagged: ${query:0:200}...(truncated)"
    send_query "$query"
}

msg_usage() {
    cat << EOF

Inspect Brew tag.

Usage:
$PROG <options>

Options:
    --tname             tag name
-i, --id                print tag id
-t, --tasks             list tasks
-n, --nvrs              list nvrs
-h, --help              display this help and exit
-v, --verbose           turn on debug
EOF
}

# Entry

DEBUG="${DEBUG:-}"
PROG="${PROG:-${0##*/}}"
tag_id="${tag_id:-}"
GET_TASKS="${GET_TASKS:-}"
GET_NVRS="${GET_NVRS:-}"
GET_TAG_ID="${GET_TAG_ID:-}"
BREWHUB="${BREWHUB:-https://brewhub.engineering.redhat.com/brewhub}"

# http://wiki.bash-hackers.org/howto/getopts_tutorial
opt_str="$@"
opt=$(getopt -n "$0" --options "hvtni" --longoptions "help,verbose,tasks,nvrs,id,tname:" -- "$@")
eval set -- "$opt"
while [[ $# -gt 0 ]]; do
    case "$1" in
        --tname)
            tag_id="$2"
            shift 2
            ;;
        -t|--tasks)
            GET_TASKS="yes"
            shift
            ;;
        -n|--nvrs)
            GET_NVRS="yes"
            shift
            ;;
        -i|--id)
            GET_TAG_ID="yes"
            shift
            ;;
        -v|--verbose)
            DEBUG="yes"
            shift
            ;;
        -h|--help)
            msg_usage
            exit 0
            ;;
        --)
            shift
            ;;
        *)
            msg_usage
            exit 1
    esac
done

# Test correct invocation
if [ -z "$tag_id" ]; then
  echo "Use: $PROG -h for help."
  exit
fi

debug "Tag: $tag_id"

if [[ -n "$GET_NVRS" || -n "$GET_TASKS" ]]; then
    list_tagged="$(brew_list_tagged "$tag_id")"
    if [ -n "$GET_NVRS" ]; then
        nvrs="$(tagged2nvrs "$list_tagged")"
        echo "$nvrs"
    elif [ -n "$GET_TASKS" ]; then
        tasks_id="$(tagged2tasks "$list_tagged")"
        echo "$tasks_id"
    fi
    exit 0
fi

if [ -n "$GET_TAG_ID" ]; then
    tag="$(brew_get_tag "$tag_id")"
    tag_id="$(tag_info2tag_id "$tag")"
    echo "$tag_id"
    exit 0
fi

echo "Use: $PROG -h for help."
exit 1
