#!/bin/bash -efu

shopt -s extglob

# 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. 2018, 2023
# Author: Andrei Stepanov <astepano@redhat.com>

# 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

RET_NO_RPMS_IN_BREW=7
RET_NO_RPMS_IN_REPOS=8
RET_EMPTY_REPOQUERY=11

task_result2rpms() {
    local arch="$1" && shift
    local xml="$1" && shift
    local rpms
    rpms="$(xml_get_value "$xml" '//member[name="rpms"]//value/string/text()' | sed -n -e "/\.$arch\.rpm/p")"
    # e.g. tasks/7171/57387171/libcap-static-2.48-9.el9_0.x86_64.rpm. Don't strip the prefix off here, we need it.
    debug "$arch rpms:\n${rpms}\n---"
    echo "$rpms"
}

task_result2srpm() {
    local xml="$1" && shift
    local srpm
    srpm="$(xml_get_value "$xml" '//member[name="srpms"]//value/string/text()' | sed -n -e "/\.rpm/p" | head -1)"
    # e.g. tasks/3126/110193126/keyutils-1.6.3-1.fc40.src.rpm. Don't strip the prefix off here, we need it.
    debug "srpm: ${srpm}\n---"
    echo "$srpm"
}

task_request2is_scratch() {
    local xml="$1" && shift
    local is_scratch
    is_scratch="$(xml_get_value "$xml" '//member[name="scratch"]/value/boolean/text()' | head -1)"
    [[ "$is_scratch" == '1' ]] && is_scratch="yes" || is_scratch="no"
    debug "Is scratch: $is_scratch"
    echo "$is_scratch"
}

task_request2is_draft() {
    local xml="$1" && shift
    local is_draft
    is_draft="$(xml_get_value "$xml" '//member[name="draft"]/value/boolean/text()' | head -1)"
    [[ "$is_draft" == '1' ]] && is_draft="yes" || is_draft="no"
    debug "Is draft: $is_draft"
    echo "$is_draft"
}

build2volume_name() {
    local xml="$1" && shift
    local volume_name
    volume_name="$(xml_get_value "$xml" '//member[name="volume_name"]/value/string/text()' | head -1)"
    debug "Volume name: $volume_name"
    echo "$volume_name"
}

build2build_source() {
    local xml="$1" && shift
    local build_source
    build_source="$(xml_get_value "$xml" '//member[name="source"]/value/string/text()' | head -1)"
    debug "Build source: $build_source"
    echo "$build_source"
}

builds2nvr() {
    local xml="$1" && shift
    local nvr
    nvr="$(xml_get_value "$xml" '//member[name="nvr"]/value/string/text()' | head -1)"
    debug "NVR: $nvr"
    echo "$nvr"
}

builds2build_id() {
    local xml="$1" && shift
    local buildid
    buildid="$(xml_get_value "$xml" '//member[name="build_id"]/value/int/text()' | head -1)"
    debug "Build id: $buildid"
    echo "$buildid"
}

builds2is_draft() {
    local xml="$1" && shift
    local is_draft
    is_draft="$(xml_get_value "$xml" '//member[name="draft"]/value/boolean/text()' | head -1)"
    [[ "$is_draft" == '1' ]] && is_draft="yes" || is_draft="no"
    debug "Is draft: $is_draft"
    echo "$is_draft"
}

buildtags_from_answer() {
    local xml="$1" && shift
    local tags
    tags="$(xml_get_value "$xml" '//member[name="name"]/value/string/text()')"
    debug "Build tags:\n${tags}\n---"
    echo "$tags"
}

children_from_answer() {
    local xml="$1" && shift
    local children
    children="$(xml_get_value "$xml" '//member[name="id"]/value/int/text()')"
    debug "Task children:\n${children}\n---"
    echo "$children"
}

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

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

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

brew_list_build_tags() {
    # listTags query
    # Build can be: build number.
    local build="$1" && shift
    local query="$(cat << EOF
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>listTags</methodName>
  <params>
    <param>
      <value><int>$build</int></value>
    </param>
  </params>
</methodCall>
EOF
    )"
#    debug "Brew query for listTags: ${query:0:200}...(truncated)"
    send_query "$query"
}

brew_list_build_rpms() {
    # listBuildRPMs query
    # Build can be: NVR or build number.
    local build="$1" && shift
    local re='^[0-9]+$'
    [[ $build =~ $re ]] && build="<int>$build</int>"
    local query="$(cat << EOF
<?xml version="1.0" encoding="UTF-8"?>
<methodCall>
  <methodName>listBuildRPMs</methodName>
  <params>
    <param>
      <value>$build</value>
    </param>
  </params>
</methodCall>
EOF
    )"
#    debug "Brew query for listBuildRPMs: ${query:0:200}...(truncated)"
    send_query "$query"
}

brew_list_builds() {
    # listBuilds query - state 1 is koji.BUILD_STATES 'COMPLETE'
    local task="$1" && shift
    local query="$(cat << EOF
<?xml version='1.0'?>
<methodCall>
  <methodName>listBuilds</methodName>
  <params>
    <param>
      <value><struct>
        <member>
          <name>__starstar</name>
          <value><boolean>1</boolean></value>
        </member>
        <member>
          <name>taskID</name>
          <value><int>$task</int></value>
        </member>
        <member>
          <name>state</name>
          <value><int>1</int></value>
        </member>
      </struct></value>
    </param>
  </params>
</methodCall>
EOF
    )"
#    debug "Brew query for listBuilds: ${query:0:200}...(truncated)"
    send_query "$query"
}

brew_get_task_result() {
    # getTaskResult query
    # Task: ID of task queried
    local task_id="$1" && shift
    local query="$(cat << EOF
<?xml version='1.0'?>
<methodCall>
    <methodName>getTaskResult</methodName>
    <params>
        <param>
            <value><int>$task_id</int></value>
        </param>
    </params>
</methodCall>
EOF
    )"
#    debug "Brew query for getTaskResult: ${query:0:200}...(truncated)"
    send_query "$query"
}

brew_get_user() {
    # getUser query
    local user_id="$1" && shift
    local query="$(cat << EOF
<?xml version='1.0'?>
<methodCall>
  <methodName>getUser</methodName>
  <params>
    <param>
      <value><int>$user_id</int></value>
    </param>
  </params>
</methodCall>
EOF
    )"
#    debug "Brew query for getUser: ${query:0:200}...(truncated)"
    send_query "$query"
}

brew_get_task_info() {
    # getTaskInfo query
    local task_id="$1" && shift
    local query="$(cat << EOF
<?xml version='1.0'?>
<methodCall>
  <methodName>getTaskInfo</methodName>
  <params>
    <param>
      <value><int>$task_id</int></value>
    </param>
  </params>
</methodCall>
EOF
    )"
#    debug "Brew query for getTaskInfo: ${query:0:200}...(truncated)"
    send_query "$query"
}

brew_get_task_request() {
    # getTaskRequest query
    local task_id="$1" && shift
    local query="$(cat << EOF
<?xml version='1.0'?>
<methodCall>
  <methodName>getTaskRequest</methodName>
  <params>
    <param>
      <value><int>$task_id</int></value>
    </param>
  </params>
</methodCall>
EOF
    )"
#    debug "Brew query for getTaskRequest: ${query:0:200}...(truncated)"
    send_query "$query"
}

taskinfo2owner() {
    local xml="$1" && shift
    local owner
    owner="$(xml_get_value "$xml" '//member[name="owner"]/value/int/text()' | head -1)"
    debug "Task owner id:\n${owner}\n---"
    echo "$owner"
}

taskinfo2method() {
    local xml="$1" && shift
    local method
    method="$(xml_get_value "$xml" '//member[name="method"]/value/string/text()' | head -1)"
    debug "Method:\n${method}\n---"
    echo "$method"
}

task_request2target() {
    local xml="$1" && shift
    local target
    target="$(xml_get_value "$xml" '//params/param[1]/value/array/data[1]/value[2]/string/text()' | head -1)"
    debug "Task target:\n${target}\n---"
    echo "$target"
}

build_rpms_info2rpms() {
    local arch="$1" && shift  # architecture
    local xml="$1" && shift   # listBuildRPMs response
    rpms="$(xml_get_value "$xml" "//member[value/string='$arch']/../member[name='nvr']/value/string/text()")"
    if [[ -n "${rpms}" ]]; then
        # Add .{arch}.rpm to each line
        declare -a lines
        while IFS= read -r line; do
            lines+=("${line}.${arch}.rpm")
        done <<< "$rpms"
        rpms=$(printf "%s\n" "${lines[@]}")
    fi
    debug "${arch} rpms:\n${rpms}\n---"
    echo "$rpms"
}

ownerinfo2user() {
    local xml="$1" && shift
    local owner
    owner="$(xml_get_value "$xml" '//member[name="name"]/value/string/text()' | head -1)"
    debug "Task owner name:\n${owner}\n---"
    echo "$owner"
}

ownerinfo2krb() {
    local xml="$1" && shift
    local email
    email="$(xml_get_value "$xml" '//member[name="krb_principal"]/value/string/text()' | head -1)"
    debug "Task owner kerberos:\n${email}\n---"
    echo "$email"
}

brew_get_task_children() {
    # getTaskChildren query
    local task_id="$1" && shift
    local query="$(cat << EOF
<?xml version='1.0'?>
<methodCall>
    <methodName>getTaskChildren</methodName>
    <params>
        <param>
            <value><int>$task_id</int></value>
        </param>
    </params>
</methodCall>
EOF
    )"
#    debug "Brew query for getTaskChildren: ${query:0:200}...(truncated)"
    send_query "$query"
}


mk_repo() {
    local task_id="$1" && shift
    local repo_dir="$1" && shift
    local repo_enabled="${1:0}" && shift
    repo_dir="${repo_dir##/}"
    repo_dir="${repo_dir%%/}"
    local repo
    repo="$(cat << EOF
[brew-${task_id}]
name=Repo for $task_id Brew build
baseurl=file:///${repo_dir}/
enabled=$repo_enabled
gpgcheck=0
EOF
    )"
    debug "Repo file text: ${repo:0:200}...(truncated)"
    echo "$repo"
}

mk_named_repo() {
    local repo_name="$1" && shift
    local repo_dir="$1" && shift
    local repo_enabled="${1:0}" && shift
    repo_dir="${repo_dir##/}"
    repo_dir="${repo_dir%%/}"
    local repo
    repo="$(cat << EOF
[${repo_name}]
name=Repo for $repo_name
baseurl=file:///${repo_dir}/
enabled=$repo_enabled
gpgcheck=0
module_hotfixes=1
EOF
    )"
    debug "Repo file text: ${repo:0:200}...(truncated)"
    echo "$repo"
}

msg_usage() {
    cat << EOF

Get RPM for Brew task.

Usage:
$PROG <options>

Options:
-a, --arch=ARCH         download for specified ARCH
-r, --recursive         download also from child tasks
-c, --createrepo        create a repo metadata at REPODIR
-t, --task=TASKID       Task ID
-i, --installrepofile   add to this system a .repo file for REPODIR
-d, --download=REPODIR  download RPM to REPODIR
-s, --srpm              print only SRPM information, URL, pkgname
    --onlyinrepo        do not download RPMs that are absent in official repos
    --repofilename      used as /etc/yum.repos.d/REPOFILENAME.repo
    --owner             print only owner information
-h, --help              display this help and exit
-v, --verbose           turn on debug
EOF
}

from_rpm_name() {
    # Input: 1:bar-9-123a.ia64.rpm or foo-1.0-1.i386
    # Mimic splitFilename() from https://github.com/rpm-software-management/yum/blob/master/rpmUtils/miscutils.py
    local filename="$1" && shift
    # One of: name, ver, rel, epoch, arch
    local req_info="$1" && shift
    # Drop .rpm
    filename="${filename%%.rpm}"
    # Arch
    local arch="${filename##*.}"
    debug "${filename} arch: ${arch}"
    [[ $req_info == 'arch' ]] && echo "$arch" && return
    # Release
    local rel="${filename##*-}"
    rel="${rel%.*}"
    debug "${filename} rel: ${rel}"
    [[ $req_info == 'rel' ]] && echo "$rel" && return
    # Version
    local ver="${filename%-${rel}.${arch}}"
    ver="${ver##*-}"
    debug "${filename} ver: ${ver}"
    [[ $req_info == 'ver' ]] && echo "$ver" && return
    # Name
    local epoch_name="${filename%-${ver}-${rel}.${arch}}"
    name="${epoch_name##*:}"
    debug "${filename} name: ${name}"
    [[ $req_info == 'name' ]] && echo "$name" && return
    # Epoch
    local epoch="${epoch_name%${name}}"
    epoch="${epoch//:/}"
    debug "${filename} epoch: ${epoch:-none}"
    [[ $req_info == 'epoch' ]] && echo "$epoch" && return
}

filter_available() {
    local rpms="$1" && shift
    local rpms_filtered=
    local name=
    for rpm in $rpms; do
        rpm_file="$(basename "$rpm")"
        name="$(from_rpm_name "${rpm_file}" "name")"
        "$YUMDNFCMD" info "${name}" >/dev/null 2>&1
        ret="$?"
        if [ "$ret" -ne 0 ]; then
            echo "Skipping as it is absent in shipped repos: $name" >&2
            continue
        fi
        rpms_filtered="${rpms_filtered:+$rpms_filtered }${rpm}"
    done
    echo "$rpms_filtered"
}

download_rpm() {
    local url="$1" && shift
    if [ -z "$DOWNLOAD" ]; then
        return
    fi
    mkdir -p "$REPODIR"
    REPODIR="$(readlink -f "$REPODIR")"
    pushd "$REPODIR" > /dev/null
    curl --retry 5 --insecure --fail --location --show-error --remote-name "$url"
    popd > /dev/null
}

mk_url() {
    local filename="$1" && shift
    local srpm_filename="$1" && shift
    local nvr="$1" && shift
    local is_scratch="$1" && shift
    local is_draft="$1" && shift
    if [ "$is_scratch" == "no" ]; then
        filename=$(basename "$filename")
        srpm_filename=$(basename "$srpm_filename")
        name="$(from_rpm_name "${srpm_filename}" "name")"
        ver="$(from_rpm_name "${srpm_filename}" "ver")"
        rel="$(from_rpm_name "${srpm_filename}" "rel")"
        if [ "$is_draft" == "yes" ]; then
            # Promoted drafts are still draft=yes in Brew while the NVR no longer
            # contains ",draft_<id>"; RPMs are then under the normal release path.
            if [[ "$nvr" == *,draft_* ]]; then
                rel="$rel",draft_${nvr#*,draft_}
            fi
        fi
        arch="$(from_rpm_name "${filename}" "arch")"
        # https://download.devel.redhat.com/brewroot/packages/curl/7.61.1/34.el8/x86_64/curl-7.61.1-34.el8.x86_64.rpm
        # https://kojipkgs.fedoraproject.org//packages/packit/0.87.1/1.fc40/src/packit-0.87.1-1.fc40.src.rpm
        url="${BREWROOT}/packages/${name}/${ver}/${rel}/${arch}/$filename"
    else
        # https://download.devel.redhat.com/brewroot/work/tasks/237/57520237/curl-7.61.1-34.el8.x86_64.rpm
        # https://kojipkgs.fedoraproject.org//work/tasks/9873/109769873/packit-0.87.1-1.fc40.src.rpm
        url="${BREWROOT}/work/${filename}"
    fi
    debug "URL for ${filename}: ${url}"
    echo "$url"
}

# Entry

: "${PROG:=${0##*/}}"
: "${ARCH:=$(uname -m)}"
: "${DEBUG:=}"
: "${TASK:=}"
: "${SRPM:=}"
: "${OWNER:=}"
: "${REPOFILENAME:=}"
: "${REPODIR:=repodir}"
: "${BREWHUB:=https://brewhub.engineering.redhat.com/brewhub}"
: "${DOWNLOAD:=}"
: "${BREWROOT:=https://download.devel.redhat.com/brewroot}"
: "${RECURSIVE:=}"
: "${CREATEREPO:=}"
: "${ONLYINREPO:=}"
: "${CREATEREPO_BIN:=}"
: "${INSTALLREPOFILE:=}"

#opt_str="$@"
opt=$(getopt -n "$0" --options "hvrd:t:a:cis" --longoptions "help,verbose,repofilename:,download:,task:,arch:,createrepo,installrepofile,onlyinrepo,owner,recursive,srpm" -- "$@")
eval set -- "$opt"
while [[ $# -gt 0 ]]; do
    case "$1" in
        -t|--task)
            TASK="$2"
            shift 2
            ;;
        -a|--arch)
            ARCH="$2"
            shift 2
            ;;
        -d|--download)
            DOWNLOAD="yes"
            REPODIR="$2"
            shift 2
            ;;
        -c|--createrepo)
            CREATEREPO="yes"
            shift
            ;;
        -s|--srpm)
            SRPM="yes"
            shift
            ;;
        --owner)
            OWNER="yes"
            shift
            ;;
        -r|--recursive)
            RECURSIVE="yes"
            shift
            ;;
        --onlyinrepo)
            ONLYINREPO="yes"
            shift
            ;;
        -i|--installrepofile)
            INSTALLREPOFILE="yes"
            shift
            ;;
        --repofilename)
            REPOFILENAME="$2"
            shift 2
            ;;
        -v|--verbose)
            DEBUG="yes"
            shift
            ;;
        -h|--help)
            msg_usage
            exit 0
            ;;
        --)
            shift
            ;;
        *)
            msg_usage
            exit 1
    esac
done

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

mkdir -p "${LOGS_DIR:=mtps-logs}"
LOGS_DIR="$(readlink -f "$LOGS_DIR")"
while true; do
    TESTRUN_ID="$(date +%H%M%S)"
    logfname="${LOGS_DIR%%/}/${TESTRUN_ID}-${TASK}-mtps-get-task.log"
    logfname_skip="$(dirname "$logfname")/SKIP-$(basename "$logfname")"
    logfname_pass="$(dirname "$logfname")/PASS-$(basename "$logfname")"
    logfname_fail="$(dirname "$logfname")/FAIL-$(basename "$logfname")"
    logfname_warn="$(dirname "$logfname")/WARN-$(basename "$logfname")"
    if [[ -e "$logfname" || -e "$logfname_pass" || -e "$logfname_fail" ]]; then
        sleep 1
        continue
    fi
    break
done
exec &> >(tee -a "$logfname")
exec 2>&1

do_clean_exit() {
    rc=$?
    trap - SIGINT SIGTERM SIGABRT EXIT # clear the trap
    new_logfname="$logfname_fail"
    if [[ "$rc" -eq 0 ]]; then
        new_logfname="$logfname_pass"
    elif [[ "$rc" -eq $RET_NO_RPMS_IN_BREW ]]; then
        new_logfname="$logfname_skip"
    elif [[ "$rc" -eq $RET_NO_RPMS_IN_REPOS || "$rc" -eq $RET_EMPTY_REPOQUERY ]]; then
        new_logfname="$logfname_warn"
    fi
    # Close tee pipes
    for pid in $(ps -o pid --no-headers --ppid $$); do
        if [ -n "$(ps -p $pid -o pid=)" ]; then
            kill -s HUP $pid
        fi
    done
    mv -f "$logfname" "$new_logfname"
    exit $rc
}

trap do_clean_exit SIGINT SIGTERM SIGABRT EXIT

debug "Task: $TASK"
debug "Arch: $ARCH"
debug "Srpm: $SRPM"
debug "Owner: $OWNER"
debug "Store RPMS at: ${REPODIR}"
debug "Create repo: ${CREATEREPO:-no}"
debug "Download recursively from children tasks: ${RECURSIVE:-no}"

task_info="$(brew_get_task_info "$TASK")"
task_owner_id="$(taskinfo2owner "$task_info")"
owner_info="$(brew_get_user "$task_owner_id")"
task_request="$(brew_get_task_request "$TASK")"
is_scratch="$(task_request2is_scratch "$task_request")"
is_draft="$(task_request2is_draft "$task_request")"

echo "Owner user: $(ownerinfo2user "$owner_info")"
echo "Owner krb: $(ownerinfo2krb "$owner_info")"
echo "Task target: $(task_request2target "$task_request")"
echo "Is scratch build: $is_scratch"
echo "Is draft build: $is_draft"

if [ -n "$OWNER" ]; then
    # Print only owner information
    exit 0
fi

# Works only for parent task
listbuilds="$(brew_list_builds "$TASK")"
nvr="$(builds2nvr "$listbuilds")"
buildid="$(builds2build_id "$listbuilds")"
listbuildtags="$(brew_list_build_tags "$buildid")"
buildtags="$(buildtags_from_answer "$listbuildtags")"
buildtags="$(echo "$buildtags" | tr '\n' ' ')"
buildtags="${buildtags%% }"

echo "BUILD ID: $buildid"
echo "BUILD TAGS: $buildtags"

task_method="$(taskinfo2method "$task_info")"
debug "task_method: $task_method"
if [[ "$task_method" == "build" ]]; then
    TASKS="$TASK"
    if [ -n "$RECURSIVE" ]; then
        task_children="$(brew_get_task_children "$TASK")"
        task_children="$(children_from_answer "$task_children")"
        TASKS="$TASKS $task_children"
        TASKS="${TASKS%% }"
    fi

    srpm_url=
    volume_name=
    build_source=
    srpm_pkg_file=
    srpm_pkg_name=
    rpms_arch_all=""
    rpms_noarch_all=""
    for task in $TASKS; do
        task_result="$(brew_get_task_result "$task")" # Holds plain XML
        rpms_from_task="$(task_result2rpms "$ARCH" "$task_result")"
        rpms_from_task_noarch="$(task_result2rpms "noarch" "$task_result")"
        srpm="$(task_result2srpm "$task_result")"
        if [ -n "$srpm" ]; then
            srpm_pkg_file="$(basename "$srpm")"
            srpm_pkg_name="$(from_rpm_name "${srpm_pkg_file}" "name")"
            if [ -z "$nvr" ]; then
                nvr="${srpm_pkg_file%%.src.rpm}"
            fi
            build="$(brew_get_build "$nvr")"
            volume_name="$(build2volume_name "$build")"
            build_source="$(build2build_source "$build")"
            srpm_url="$(mk_url "$srpm" "$srpm_pkg_file" "$nvr" "$is_scratch" "$is_draft")"
        fi
        rpms_arch_all+=" $rpms_from_task"
        rpms_noarch_all+=" $rpms_from_task_noarch"
    done

    # remove trailing whitespaces
    rpms_arch_all="${rpms_arch_all%%+( )}"
    rpms_noarch_all="${rpms_noarch_all%%+( )}"

    echo "NVR: $nvr"
    echo "SRPM PKG NAME: $srpm_pkg_name"
    echo "SRPM PKG FILE: $srpm_pkg_file"
    echo "SRPM URL: $srpm_url"
    echo "BUILD SOURCE: $build_source"

    if [ -n "$SRPM" ]; then
        # Print only SRPM information
        exit 0
    fi
# Builds imported from Konflux don't have descendant/child tasks to take the (S)RPMs from.
# This is much easier than taking the (S)RPMs from (sub)task(s)
# but can't be used for the 'build' method because of scratch builds (they don't have build id)
elif [[ "$task_method" == "cg_import" ]]; then
    build_rpms="$(brew_list_build_rpms "$buildid")"
    rpms_arch_all="$(build_rpms_info2rpms "$ARCH" "$build_rpms")"
    rpms_noarch_all="$(build_rpms_info2rpms "noarch" "$build_rpms")"
    srpm_pkg_file="$(build_rpms_info2rpms "src" "$build_rpms")"
    # Import tasks don't tell you if the build is a draft, so determine it from the build
    # otherwise the URL will be constructed incorrectly
    is_draft="$(builds2is_draft "$listbuilds")"
else
    echo "Unknown Brew method: $task_method"
    exit 1
fi

if [ -z "${rpms_arch_all}${rpms_noarch_all}" ]; then
    echo "There are no ${ARCH}/noarch RPMs for Brew/Koji task ${TASK}"
    exit "$RET_NO_RPMS_IN_BREW"
fi

if [ -n "$ONLYINREPO" ]; then
    # Purpose:
    #
    #   * Brew builds always have 1 input SRPM.
    #   * Brew builds can have many RPMs.
    #
    # RCM team can choose only some RPM. And make AppStream / BaseOS / Compose
    # only from some RPMs, ignoring other RPMs from Brew build. This options
    # says to ignore RPMs that are absent.
    rpms_arch_all="$(filter_available "$rpms_arch_all")"
    rpms_noarch_all="$(filter_available "$rpms_noarch_all")"
fi

if [ -z "${rpms_arch_all}${rpms_noarch_all}" ]; then
    # all packages have been filtered out above
    echo "None of the packages is available in repos. Is it a new package?"
    exit "$RET_NO_RPMS_IN_REPOS"
fi

declare -A urls # associative array (dictionary, map)
for pkg in $rpms_arch_all $rpms_noarch_all; do
    url="$(mk_url "$pkg" "$srpm_pkg_file" "$nvr" "$is_scratch" "$is_draft")"
    urls["$url"]=1 # in order to deduplicate, store url as key, value is unimportant
done

# Iterate over keys
for url in "${!urls[@]}"; do
    echo "$url"
    download_rpm "$url"
done

if [[ -z "$CREATEREPO" || ! -d "$REPODIR" ]]; then
    echo "Not creating repo"
    exit 0
fi

which 'createrepo' >/dev/null 2>&1 && CREATEREPO_BIN="createrepo" || :
which 'createrepo_c' >/dev/null 2>&1 && CREATEREPO_BIN="createrepo_c" || :
if [ -z "$CREATEREPO_BIN" ]; then
    echo "Install createrepo[_c] to create repositories."
    exit 1
fi
echo "Using $CREATEREPO_BIN"
"$CREATEREPO_BIN" --database "$REPODIR"

if [ -n "$REPOFILENAME" ]; then
    repo_file_text="$(mk_named_repo "$REPOFILENAME" "$REPODIR" "1")"
    repo_name="$REPOFILENAME"
else
    repo_file_text="$(mk_repo "$TASK" "$REPODIR" "1")"
    repo_name="brew-${TASK}"
fi

id="$(id -u)"
if [[ -n "$INSTALLREPOFILE" && "$id" -eq 0 ]]; then
    repofile="/etc/yum.repos.d/${repo_name}.repo"
    echo "Creating repo file: $repofile"
    echo "$repo_file_text" > "$repofile"
fi
echo "Repo file content:"
echo "$repo_file_text"

# shellcheck disable=SC2086
# Query packages in the created repo
nevras_in_repo="$(
    ${REPOQUERYCMD} --repoid="$repo_name" '*' \
        --qf "%{repoid} %{name}-%{epoch}:%{version}-%{release}.%{arch}${REPOQUERY_SEPARATOR:-}" 2>&1 | \
        sed -n -e "/^${repo_name}[[:space:]]/ s/^${repo_name}[[:space:]]//p"
)"
# Exclude SRPMs
nevras_in_repo="$(echo "$nevras_in_repo" | sed -n -e "/\.src$/d;p")"

if [ -z "${nevras_in_repo// /}" ]; then
    # Yum/dnf thinks there are no packages in the testing repo.
    # This usually happens when the packages are filtered out
    # because they (different version-release) are included
    # in an (enabled) module.
    exit "$RET_EMPTY_REPOQUERY"
fi
