#!/bin/bash

# Copyright (c) Veeam Software Group GmbH

set -eE -u -o pipefail

SCRIPT_DIR=$(dirname "$(realpath "${BASH_SOURCE[0]}")"); readonly SCRIPT_DIR;
source "$SCRIPT_DIR/lib/error-handle.bash"
source "$SCRIPT_DIR/lib/optparser.bash"

setlocale en_US.utf8 || :

# shellcheck disable=SC2034
declare -A op=()
declare -A ARGS=()
optparser-init op --desc "List available packages with PostgreSQL database."
optparser-addopt op --name "version-pattern" --narg '?' \
    --help "version pattern"
optparser-addopt op -s "-i" -l "--installed" \
    --help "display only installed packages"
optparser-addopt op -s "-m" -l "--module" \
    --help "include module information"
optparser-addopt op -s "-L" -l "--no-legend" \
    --help "disable the column headers"
optparser-addopt op -s "-t" -l "--tsv" \
    --help "output in the tab-separated format"
optparser-addopt op -s "-h" -l "--help" \
    --help "show this help message and exit"
optparser-parse op ARGS "$@" || exit 1
[[ -n ${ARGS[help]:-} ]] && { optparser-help op; exit 0; }

declare -A os_release
parse-os-release os_release
case "${os_release[ID]}" in
    rocky | rhel) ;;
    *) die "unsupported OS \"${os_release[PRETTY_NAME]}\"" ;;
esac

trap-init

declare -a dnfargs=(
    -qy repoquery --qf "%{name} %{version}-%{release} %{reponame}"
    --whatprovides "postgresql-server"
)

if [[ -n ${ARGS[installed]:-} ]]; then
    dnfargs+=("--installed")
else
    dnfargs+=("--disable-modular-filtering")
fi

if [[ -n ${ARGS[tsv]:-} ]]; then
    readonly fmt="%s\t%s\t%s${ARGS[module]:+\t}%s\n"
else
    readonly fmt="%-20s %-40s %-25s${ARGS[module]:+ }%s\n"
fi

#shellcheck disable=SC2059
[[ -z ${ARGS[no-legend]:-} ]] \
    && printf "$fmt" "package name" "version" "repository" "${ARGS[module]:+module}"

dnf "${dnfargs[@]}" | sort -V -k 2 | while IFS=$' ' read -r -a line; do
    name=${line[0]}
    version=${line[1]}
    repo=${line[2]:-}
    #shellcheck disable=SC2053
    if [[ -z ${ARGS[version-pattern]:-} ]] || [[ $version = ${ARGS[version-pattern]:-} ]]; then
        if [[ -n ${ARGS[module]:-} ]]; then
            module=$({
                dnf -qy module provides "${line[0]}-${line[1]}" \
                    | sed -ne 's/^Module\s*:\s*\(.\+\)/\1/p' \
                    | tail -1
            })
        fi
        #shellcheck disable=SC2059
        printf "$fmt" "$name" "$version" "$repo" "${module:-}"
    fi
done
