#!/bin/bash

#  Name:    br-install
#  Author:  Terry Neve
#  Created: Feb 2022
#
#  Program to determine and install build dependencies for a package.
#  It is designed to be called via Right-Click service menu in pkgutils.
#
#  The names of the packages installed are appended to <spec>.remove so that
#  rmvpkg can remove them again.  Running br-install again (e.g. after adding
#  a missing BuildRequires to the SPEC) appends to the same file.
#
#  Note: packages that were already installed (e.g. by br-install for another
#  SPEC) are not recorded, so removing that other SPEC's list removes them.
#
#  Revisions:
#       20220218.01  Initial working version
#       20240524.01  Fix for new rpmbuild flags
#       20240623.01  Create .remove files
#       20260531.01  Convert from APT to DNF
#       20260919.01  Record package names instead of transaction IDs, only
#                    write .remove when something was installed, handle
#                    %generate_buildrequires

SPEC_FILE=$1
REMOVE_FILE="${SPEC_FILE}.remove"
HEADER="# pkgutils-remove v1"
MAX_ROUNDS=10
RECORDED=0

if [ -z "$SPEC_FILE" ] || [[ ! $SPEC_FILE =~ \.spec$ ]]; then
    echo "Usage: $0 <path-to-spec-file>"
    exit 1
fi

if [ ! -f "$SPEC_FILE" ]; then
    echo "Error: $SPEC_FILE not found."
    exit 1
fi

if [ $UID -eq 0 ]; then
    echo "Please use this command as normal user, not root."
    exit 1
fi

# Highest transaction ID in dnf5 history (0 if none)
last_txn_id () {
    dnf5 history list --json 2>/dev/null | jq '[.[].id] | max // 0'
}

# Run dnf5 builddep on a spec or (nosrc) srpm and record what it installed.
# Returns 0 if packages were installed, 1 if nothing was installed and
# 2 on error.
run_builddep () {
    local target=$1 mode=$2 before after info names

    before=$(last_txn_id)
    echo "Installing dependencies for $target..."
    if ! su -m -c "dnf5 builddep $mode $(printf '%q' "$target")"; then
        echo "Error: dnf5 builddep failed."
        return 2
    fi
    after=$(last_txn_id)

    if [ "$after" = "$before" ]; then
        echo "Nothing to install."
        return 1
    fi

    info=$(dnf5 history info "$after" --json)
    if ! jq -e '.[0].description | test("builddep")' <<< "$info" >/dev/null; then
        echo "Error: transaction $after is not a builddep transaction."
        return 2
    fi

    names=$(jq -r '.[0].packages[] | select(.action == "Install")
                   | .nevra | sub("-[0-9]+:[^-]+-[^-]+$"; "")' <<< "$info")
    if [ -z "$names" ]; then
        echo "Nothing new installed."
        return 1
    fi

    if [ ! -f "$REMOVE_FILE" ]; then
        { echo "$HEADER"; echo "# spec: $(realpath "$SPEC_FILE")"; } > "$REMOVE_FILE"
    fi
    {
        jq -r '.[0] | "# txn \(.id) \(.start_time | strflocaltime("%Y-%m-%d %H:%M")) \(.description)"' <<< "$info"
        echo "$names"
    } >> "$REMOVE_FILE"

    RECORDED=$((RECORDED + $(wc -l <<< "$names")))
    echo "Transaction $after recorded in $REMOVE_FILE"
    return 0
}

# Static BuildRequires
run_builddep "$SPEC_FILE" --spec
[ $? -eq 2 ] && exit 1

# Dynamic BuildRequires: rpmbuild -br exits 11 while generated BuildRequires
# are missing, writing a .buildreqs.nosrc.rpm that builddep can resolve.
if grep -q '^%generate_buildrequires' "$SPEC_FILE"; then
    for (( round=1; ; round++ )); do
        if [ $round -gt $MAX_ROUNDS ]; then
            echo "Error: generated BuildRequires still missing after $MAX_ROUNDS rounds."
            exit 1
        fi
        echo "Checking generated BuildRequires (round $round)..."
        OUT=$(rpmbuild -br "$SPEC_FILE" 2>&1)
        RC=$?
        [ $RC -eq 0 ] && break
        if [ $RC -ne 11 ]; then
            echo "$OUT"
            echo "Error: rpmbuild -br failed (are all sources in the SOURCES folder?)"
            exit 1
        fi
        NOSRC=$(sed -n 's/^Wrote: \(.*\.buildreqs\.nosrc\.rpm\)$/\1/p' <<< "$OUT" | tail -n 1)
        if [ -z "$NOSRC" ]; then
            echo "$OUT"
            echo "Error: could not find the buildreqs.nosrc.rpm written by rpmbuild."
            exit 1
        fi
        run_builddep "$NOSRC" --srpm
        case $? in
            1) echo "$OUT"
               echo "Error: generated BuildRequires could not be installed."
               exit 1;;
            2) exit 1;;
        esac
    done
fi

if [ $RECORDED -gt 0 ]; then
    echo "Install complete. $RECORDED package(s) recorded in $REMOVE_FILE"
else
    echo "Install complete. No new packages installed."
fi
