#!/bin/bash
# sync-modules.sh — scan apps/ and stub any missing entries in modules.conf
# Safe to run repeatedly; never removes or modifies existing entries.
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SETUP_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
CONF="$SETUP_DIR/modules.conf"
APPS="$SETUP_DIR/modules/optional-Modules/apps"

# Read all existing IDs from modules.conf into a set.
declare -A known
while IFS='|' read -r id _rest; do
    [[ "$id" =~ ^[[:space:]]*# || -z "${id// /}" ]] && continue
    known["$id"]=1
done < "$CONF"

# Scan apps/ for .sh files not yet in modules.conf and append stubs.
added=0
for script in "$APPS"/*.sh; do
    id="${script##*/}"
    id="${id%.sh}"
    if [[ -z "${known[$id]+set}" ]]; then
        printf '%s||||\n' "$id" >> "$CONF"
        echo "  [added stub] $id"
        (( added++ )) || true
    fi
done

if (( added == 0 )); then
    echo "modules.conf is up to date — no new stubs added."
else
    echo "$added stub(s) added to modules.conf. Fill in category and description, then run generate-modules.sh."
fi
