#!/bin/bash
# Coding assistance from Claude Code
#
# Check that all programs and libraries needed to build the
# stanford-server RPM are installed.

missing_packages=()

check_command() {
    if ! command -v "$1" > /dev/null 2>&1; then
        echo "MISSING: $1 (install package: $2)"
        missing_packages+=("$2")
    else
        echo "OK:      $1"
    fi
}

echo "Checking required programs..."
echo ""

check_command rpmbuild rpm-build
check_command pod2man perl-interpreter
check_command tar tar

echo ""

if [ "${#missing_packages[@]}" -eq 0 ]; then
    echo "All build dependencies are satisfied."
    exit 0
fi

deduplicated=($(printf '%s\n' "${missing_packages[@]}" | sort -u))

echo "The following packages need to be installed:"
echo ""
echo "    ${deduplicated[*]}"
echo ""

read -r -p "Install them now using dnf? [y/N] " answer

if [ "$answer" != "y" ] && [ "$answer" != "Y" ]; then
    echo "Aborted. Install the missing packages manually before building."
    exit 1
fi

echo ""
echo "Running: dnf install ${deduplicated[*]}"
echo ""

if ! dnf install -y "${deduplicated[@]}"; then
    echo ""
    echo "Installation failed. You may need to run this script with sudo."
    exit 1
fi

echo ""
echo "All build dependencies are now installed."
