#!/usr/bin/bash
#
# The Qubes OS Project, http://www.qubes-os.org
#
# Copyright (C) 2017 Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
# Copyright (C) 2018 Frédéric Pierret (fepitre) <frederic@invisiblethingslab.com>
#
# 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 the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

set -e
if [ "${VERBOSE:-0}" -ge 2 ] || [ "${DEBUG:-0}" -eq 1 ]; then
    set -x
fi

source_dir="$1"
spec_file="$2"
query_field="$3"
dist="$4"

if [ $# -lt 4 ]; then
    echo "Usage: $0 source_dir file.spec field dist" >&2
    exit 1
fi

rpm_defines=()

# make it a function and export, as bash doesn't support exporting an array
set_rpm_defines() {
    local dist="$1"
    # strip possible devel number
    raw_dist="${dist#*.}"
    if [[ "$raw_dist" = "fc"* ]]; then
        dist_ver="${raw_dist#fc}"
        rpm_defines+=(--define "fedora $dist_ver")
    elif [[ "$raw_dist" = "el"* ]]; then
        dist_ver="${raw_dist#el}"
        rpm_defines+=(--define "centos $dist_ver")
        rpm_defines+=(--define "rhel $dist_ver")
    fi
}

export -f set_rpm_defines

spec_file_bn="$(basename "${spec_file}")"

[[ "${spec_file_bn}.in" == ".in" ]] && exit 0

if [ -r "${spec_file}.in" ]; then
    #rpm -q $RPM_QUERY_DEFINES --qf "$2" --specfile <(`dirname $0`/generate-spec "${spec_file}.in" /dev/stdout) 2>/dev/null
    # need to create a file due to a bug in process substitution (e.g. artwork package)
    tmp_spec=$(mktemp --tmpdir tmp.XXXXXX.spec)
    "$(dirname "$0")/generate-spec" "$source_dir" "${spec_file}.in" "${tmp_spec}"
    if [ "${query_field}" = "%{SOURCE0}" ]; then
        spectool --list-files --source 0 "${tmp_spec}"
    elif [ "${query_field}" = "PACKAGES_LIST" ]; then
        "$(dirname "$0")"/query-builtrpms "${tmp_spec}" "$dist"
    else
        rpm -q --define "dist .$dist" --qf "${query_field}" --specfile "${tmp_spec}"
    fi
    rm -f "${tmp_spec}"
else
    if [ "${query_field}" = "%{SOURCE0}" ]; then
        spectool --list-files --source 0 "${spec_file}"
    elif [ "${query_field}" = "PACKAGES_LIST" ]; then
        "$(dirname "$0")"/query-builtrpms "${spec_file}" "$dist"
    else
        rpm -q --define "dist .$dist" --qf "${query_field}" --specfile "${spec_file}"
    fi
fi
