#!/bin/sh
set -eu

SRC="/etc/X11/fluxbox/fluxbox-menu"
DST_DIR="/var/run/retrodebian"
DST="$DST_DIR/final-fluxbox-menu"
TEMPLATE="/opt/retrodebian/fluxbox/retrodebian-menu.section"

mkdir -p "$DST_DIR"

TMP="$DST.tmp"

logger -t "fluxbox/update-menu.sh" "Regenerating menus..."

sed \
  -e '/(Eterm/d' \
  -e '/(Rxvt-Unicode (Black/d' \
  -e '/(XTerm/d' \
  "$SRC" > "$TMP.base"

if [ -f "$TEMPLATE" ]; then
    awk -v template="$TEMPLATE" '
        BEGIN { inserted = 0 }
        {
            print
            if (!inserted && $0 ~ /^\[begin\] /) {
                while ((getline line < template) > 0) {
                    print line
                }
                close(template)
                inserted = 1
            }
        }
    ' "$TMP.base" > "$TMP"
else
    mv "$TMP.base" "$TMP"
fi

rm -f "$TMP.base"
mv "$TMP" "$DST"

fluxbox-remote reconfigure >/dev/null 2>&1 || true