#!/bin/bash

#  Name:    crepo
#  Author:  Terry Neve
#  Created: May 2026
#
#  Program to create the DNF repo indexes for the local repository.
#  Part of the pkgutils suite of tools replacing the gbd tool used for APT
#
#  Revisions:
#       20260531.01  Initial working version
#       20260920.01  Move config to local.repo
#       20260920.02  Scan every *.repo file in /etc/repo.d

# Directory holding the DNF repo definitions
REPO_DIR="/etc/repo.d"

# Check if the repo directory exists and holds any repo files
if [ ! -d "$REPO_DIR" ]; then
    echo "Error: $REPO_DIR not found." >&2
    exit 1
fi

shopt -s nullglob
REPO_FILES=("$REPO_DIR"/*.repo)
shopt -u nullglob

if [ ${#REPO_FILES[@]} -eq 0 ]; then
    echo "Error: no *.repo files found in $REPO_DIR." >&2
    exit 1
fi

# Check if createrepo_c is installed
if ! command -v createrepo_c &> /dev/null; then
    echo "Error: createrepo_c is not installed or not in PATH." >&2
    exit 1
fi

# Directories already indexed, so the same repo listed twice is only done once
declare -A DONE=()
FOUND=0

# Index every [local-xxx] section found in the given repo file
scan_repo_file () {
    local repo_file=$1 line url_path local_dir
    local in_local_block=false
    local repo_name=""

    # Read the file line by line
    while IFS= read -r line; do
        # Trim leading/trailing whitespace and carriage returns
        line=$(echo "$line" | xargs)

        # Skip empty lines or lines that are completely commented out
        [[ -z "$line" || "$line" =~ ^# ]] && continue

        # Check if we are entering a [local-xxx] block
        if [[ "$line" =~ ^\[local-.*\]$ ]]; then
            in_local_block=true
            repo_name="$line"
            continue
        fi

        # If we hit a different repository block, stop tracking
        if [[ "$line" =~ ^\[.*\]$ ]]; then
            in_local_block=false
            repo_name=""
            continue
        fi

        # If we are inside a local block, look for the baseurl
        if [ "$in_local_block" = true ] && [[ "$line" =~ ^baseurl= ]]; then
            # Extract the value after baseurl=
            url_path="${line#baseurl=}"
            url_path=$(echo "$url_path" | xargs) # trim spaces

            # Strip standard local URL prefixes if they exist (file:// or file:///)
            local_dir="${url_path#file://}"
            local_dir="${local_dir#localhost}" # handles file://localhost/path
            local_dir="${local_dir#/}"         # Ensure we can clean it up
            local_dir="/$local_dir"            # Guarantee absolute path format

            # Skip a directory that another repo file already covered
            if [ -n "${DONE[$local_dir]}" ]; then
                continue
            fi
            DONE[$local_dir]=1
            FOUND=$((FOUND + 1))

            # Check if the extracted path is a valid local directory
            if [ -d "$local_dir" ]; then
                echo "--------------------------------------------------"
                echo "Found Local Repo: $repo_name ($repo_file)"
                echo "Target Directory: $local_dir"
                echo "Running createrepo_c..."

                # Run the command
                if createrepo_c "$local_dir"; then
                    echo "Successfully updated repository metadata."
                else
                    echo "Warning: createrepo_c failed on $local_dir" >&2
                fi
            else
                echo "--------------------------------------------------"
                echo "Skipping $repo_name: '$local_dir' is not a valid directory or not local." >&2
            fi
        fi

    done < "$repo_file"
}

echo "Scanning $REPO_DIR for local repositories..."

for f in "${REPO_FILES[@]}"; do
    scan_repo_file "$f"
done

echo "--------------------------------------------------"
if [ $FOUND -eq 0 ]; then
    echo "No [local-*] repositories found in $REPO_DIR/*.repo"
    exit 1
fi
echo "Scan complete."

echo -ne "\nUpdate package list? [y/N] "
read u
case $u in
        y|Y)    echo -ne "\nPlease enter root "
                su -c "dnf makecache --refresh";;
esac
