#!/bin/bash
# gen-changelog.sh - Generate and append to AM·OS CHANGELOG.txt
set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
REPO="$(cd -- "$SCRIPT_DIR/.." && pwd -P)"
TREE="$REPO/amos64"
OLD_LOG="$REPO/CHANGELOG.txt"
SLACK_LOG="$(cd -- "$SCRIPT_DIR/../../../slackware-current/repo" && pwd -P)/ChangeLog.txt"
TODAY=$(date -u '+%a %b %d %H:%M:%S UTC %Y')

NEW_LIST=$(mktemp)
OLD_LIST=$(mktemp)
DIFF_LIST=$(mktemp)
TEMP_ENTRY=$(mktemp)
trap 'rm -f "$NEW_LIST" "$OLD_LIST" "$DIFF_LIST" "$TEMP_ENTRY"' EXIT

# 1. List all current packages in our custom output tree
# Fixed the glob pattern to explicitly match Slackware package extensions.
find "$TREE" -type f \( -name '*.txz' -o -name '*.tgz' -o -name '*.tbz' -o -name '*.tlz' \) -printf '%P\n' | sort -u > "$NEW_LIST"

# 2. Extract already-logged packages from CHANGELOG.txt
# If the log doesn't exist or is empty, OLD_LIST remains empty.
if [ -f "$OLD_LOG" ] && [ -s "$OLD_LOG" ]; then
    grep -E '^[a-z]+/.*\.t?[gx]z:' "$OLD_LOG" | awk '{print $1}' | sed 's/:$//' | sort -u > "$OLD_LIST" || true
else
    touch "$OLD_LIST"
fi

# 3. Find packages in the tree that are NOT in the changelog
comm -13 "$OLD_LIST" "$NEW_LIST" > "$DIFF_LIST"

# 4. If no changes, exit cleanly
if [ ! -s "$DIFF_LIST" ]; then
    echo "No new changes detected. CHANGELOG.txt is up to date."
    exit 0
fi

# 5. Build the new changelog entry
echo "+--------------------------+" > "$TEMP_ENTRY"
echo "$TODAY" >> "$TEMP_ENTRY"
echo "+--------------------------+" >> "$TEMP_ENTRY"
echo "### Note: For a-y series, technical notes and CVEs below are extracted from the upstream Slackware Linux changelog." >> "$TEMP_ENTRY"
echo "" >> "$TEMP_ENTRY"

while IFS= read -r pkg_path; do
    echo "$pkg_path:  Upgraded." >> "$TEMP_ENTRY"
    
    # Match this specific package path in the Slackware log to pull CVEs
     # Filter out social acknowledgments and thanks, somehow it doesn't feel approprite to give impression Slackware contributors handle AMOS as well. We thank them anyway
    if [ -f "$SLACK_LOG" ]; then
        awk -v path="$pkg_path" '
            $1 == path":" { found=1; next }
            found && /^[[:space:]]/ {
                line = tolower($0)
                if (line !~ /^[[:space:]]*thanks/ && line !~ /^[[:space:]]*props/ && line !~ /^[[:space:]]*credit/) {
                    print "    " $0
                }
                next
            }
            found && !/^[[:space:]]/ { found=0 }
        ' "$SLACK_LOG" >> "$TEMP_ENTRY"
    fi
done < "$DIFF_LIST"

echo "" >> "$TEMP_ENTRY"

# 6. Append to the master CHANGELOG.txt (or create it if it's the first run)
if [ -f "$OLD_LOG" ] && [ -s "$OLD_LOG" ]; then
    cat "$TEMP_ENTRY" >> "$OLD_LOG"
else
    mv "$TEMP_ENTRY" "$OLD_LOG"
fi

echo "Appended $(wc -l < "$DIFF_LIST") package updates to CHANGELOG.txt"