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

#
# This file is `source` by all mini-tps scripts
#

# What command to used for yum/dnf command defined by next priority:
# 1. Env variable MINITPSYUMDNFCMD
# 2. If /usr/bin/yum is symlink:
#
#   * read this symlink
#   * <=f40, <= c10s, <= rhel10:
#
#      lrwxrwxrwx. 1 root root 5 May 29 00:00 /usr/bin/yum -> dnf-3
#
#   * >=F41:
#
#      lrwxrwxrwx. 1 root root 4 Jul 19 00:00 /usr/bin/yum -> dnf5
#
# 3. If /usr/bin/yum is present then use `yum`
# 4. Else use `dnf`
#

YUMDNFCMD="${MINITPSYUMDNFCMD:-}"

if [ -z "$YUMDNFCMD" ]; then
    if [ -f "/usr/bin/yum" ]; then
        YUMDNFCMD="yum"
        if [ -L "/usr/bin/yum" ]; then
            YUMDNFCMD="$(readlink "/usr/bin/yum")"
        fi
    else
        YUMDNFCMD="dnf"
    fi
fi

# shellcheck disable=SC2034
# What command to use for repoquery command defined based on YUMDNFCMD:
# 1. If `yum`, then `repoquery` (from yum-utils)
# 2. If any version of `dnf`, then `dnf repoquery` (from python3-dnf or dnf5)
case "$YUMDNFCMD" in
    yum)
       REPOQUERYCMD="repoquery"
       REPOQUERY_SEPARATOR=
       REPOQUERY_SHOWDUPLICATES="--show-duplicates"
       ;;
    dnf5)
       REPOQUERYCMD="dnf5 repoquery"
       REPOQUERY_SEPARATOR="\n"
       REPOQUERY_SHOWDUPLICATES=
       ;;
    *)
       REPOQUERYCMD="dnf repoquery"
       REPOQUERY_SEPARATOR=
       REPOQUERY_SHOWDUPLICATES="--show-duplicates"
       ;;
esac

debug() {
    if [[ -n "${DEBUG:-}" || -n "${GB_DEBUG:-}" ]]; then
        echo -e "$*" >&2
    fi
}

# Portable xmllint helper: extracts a single text value via XPath.
# Works with xmllint --shell (available since RHEL 6) instead of --xpath (RHEL 7+).
# Usage: xml_get_value "$xml_string" "//member[name='foo']/value/string/text()"
xml_get_value() {
    local xml="$1" && shift
    local xpath="$1" && shift
    local tmpfile
    tmpfile="$(mktemp)"
    echo "$xml" > "$tmpfile"
    local result
    result="$(echo "cat $xpath" | xmllint --shell "$tmpfile" | sed -n -e '/^[[:alnum:]]/p')"
    rm -f "$tmpfile"
    echo "$result"
}
