#!/bin/bash
#
# reorganize_whitelist.sh
#
# Re-shuffles the ISO_WHITELIST=( ... ) array in a ghostnet profile so that
# the packages are grouped by Slackware series (a, ap, d, e, ...), using the
# real package files found under /repo/amos64/<series>/.
#
# Nothing is added and nothing is removed: every package name that already
# exists in the array is kept, just reordered / regrouped with "# <series>"
# comment headers.
#
# Usage:  bash reorganize_whitelist.sh [/repo/profiles/ghostnet_new.conf] [/repo/amos64]
#
set -euo pipefail

CONF="${1:-/repo/profiles/edge.conf}"
REPO="${2:-/repo/amos64}"

[[ -r $CONF ]] || { echo "error: cannot read '$CONF'"  >&2; exit 1; }
[[ -d $REPO ]] || { echo "error: cannot read '$REPO'"  >&2; exit 1; }

# ---------------------------------------------------------------------------
# 1. Build a package-name -> series map from the package files on disk.
#    Slackware package file: <name>-<version>-<arch>-<build>.<ext>
#    so the package name is the filename with the extension and the last
#    three '-' separated fields removed.
# ---------------------------------------------------------------------------
declare -A PKG_SERIES=()

for dir in "$REPO"/*/; do
    series=$(basename "$dir")
    for f in "$dir"*; do
        [[ -f $f ]] || continue
        base=$(basename "$f")

        # only real Slackware packages
        [[ $base =~ \.(t[xb]z|tgz|tlz|tar\.(gz|xz|bz2))$ ]] || continue

        stem=${base%.*}          # drop .txz / .tlz / .gz / .xz / .bz2
        stem=${stem%.tar}        # drop .tar if it was .tar.*

        name=$(awk -F- 'BEGIN{OFS="-"}{if (NF>3) NF=NF-3; print}' <<< "$stem")
        [[ -n $name ]] || continue

        # first series that claims a name wins
        [[ -n ${PKG_SERIES[$name]:-} ]] || PKG_SERIES[$name]=$series
    done
done

# ---------------------------------------------------------------------------
# 2. Locate the ISO_WHITELIST=( ... ) block inside the config file.
# ---------------------------------------------------------------------------
start_line=$(grep -n '^[[:space:]]*ISO_WHITELIST=(' "$CONF" | head -n1 | cut -d: -f1)
[[ -n $start_line ]] || { echo "error: 'ISO_WHITELIST=(' not found in $CONF" >&2; exit 1; }

end_line=$(awk -v s="$start_line" '
    NR < s { next }
    { l = $0; sub(/#.*/, "", l) }        # ignore comments when looking for ")"
    l ~ /\)[[:space:]]*$/ { print NR; exit }
' "$CONF")
[[ -n $end_line ]] || { echo "error: closing ')' of ISO_WHITELIST not found in $CONF" >&2; exit 1; }

# ---------------------------------------------------------------------------
# 3. Extract every package token from the block (comments stripped).
# ---------------------------------------------------------------------------
mapfile -t block < <(sed -n "${start_line},${end_line}p" "$CONF")

tokens=()
for line in "${block[@]}"; do
    line=${line%%#*}                 # strip comments
    line=${line//ISO_WHITELIST=(/}   # drop the array opener
    line=${line//)/}                 # drop the array closer
    for t in $line; do
        tokens+=("$t")
    done
done

# ---------------------------------------------------------------------------
# 4. Group the tokens by series (original order preserved inside a series).
# ---------------------------------------------------------------------------
declare -A SERIES_PKGS=()
unknown=()

for t in "${tokens[@]}"; do
    s=${PKG_SERIES[$t]:-}
    if [[ -z $s ]]; then
        unknown+=("$t")
    else
        SERIES_PKGS[$s]+="$t"$'\n'
    fi
done

# ---------------------------------------------------------------------------
# 5. Emit the new array, wrapped at ~80 columns.
# ---------------------------------------------------------------------------
emit_wrapped() {
    local prefix='  ' line=''
    local p
    for p in "$@"; do
        if [[ -z $line ]]; then
            line="${prefix}${p}"
        elif (( ${#line} + 1 + ${#p} > 80 )); then
            printf '%s\n' "$line"
            line="${prefix}${p}"
        else
            line+=" ${p}"
        fi
    done
    [[ -z $line ]] || printf '%s\n' "$line"
}

new_block=$(mktemp)

{
    echo 'ISO_WHITELIST=('

    if (( ${#SERIES_PKGS[@]} )); then
        mapfile -t series_sorted < <(printf '%s\n' "${!SERIES_PKGS[@]}" | LC_ALL=C sort)
        for s in "${series_sorted[@]}"; do
            echo "  # ${s} series"
            mapfile -t pkgs < <(printf '%s' "${SERIES_PKGS[$s]}")
            emit_wrapped "${pkgs[@]}"
            echo
        done
    fi

    if (( ${#unknown[@]} )); then
        echo "  # --- NOT FOUND under ${REPO} (kept verbatim, please review) ---"
        emit_wrapped "${unknown[@]}"
        echo
    fi

    echo ')'
} > "$new_block"

# ---------------------------------------------------------------------------
# 6. Splice the new block back into the config file (with a backup).
# ---------------------------------------------------------------------------
backup="${CONF}.bak.$(date +%Y%m%d-%H%M%S)"
cp -a "$CONF" "$backup"

tmp_out=$(mktemp)
{
    (( start_line > 1 )) && head -n $((start_line - 1)) "$CONF"
    cat "$new_block"
    tail -n +$((end_line + 1)) "$CONF"
} > "$tmp_out"

mv "$tmp_out" "$CONF"
rm -f "$new_block"

# ---------------------------------------------------------------------------
# 7. Summary
# ---------------------------------------------------------------------------
echo "Rewrote ISO_WHITELIST in $CONF"
echo "  backup : $backup"
echo "  series : ${#SERIES_PKGS[@]}"
echo "  pkgs   : ${#tokens[@]}"

if (( ${#unknown[@]} )); then
    echo "  WARNING: ${#unknown[@]} entr(y/ies) not found under $REPO:" >&2
    printf '    %s\n' "${unknown[@]}" >&2
fi