#!/bin/sh

# This script helps generate menu files for the blackbox window manager.
# It gathers its data from simple menu entry data files.

# Copyright 2002 Jeremy C. Reed
# Software is provided "as is" and all liabilities are waived.
# You may modify, use, and redistribute as long as this copyright and
# statement is included.

# later ideas:
# -x regex  to exclude
# -d  to output to console for debugging or use instead of to file

# source in the menus configuration for XTERM setting
if [ -e /usr/pkg/etc/menus.conf ] ; then
  . /usr/pkg/etc/menus.conf
fi

# allow overriding of system-wide configurations
if [ -e ~/.menus.conf ] ; then
 . ~/.menus.conf
fi

if [ -z "${XTERM}" ] ; then
  XTERM=/usr/X11R6/bin/xterm
fi
if [ -z "${MENU_CONF_DIR}" ] ; then
  MENU_CONF_DIR=/usr/pkg/etc/menus
fi
if [ -z "${BLACKBOX_MENU_FILE}" ] ; then
  BLACKBOX_MENU_FILE=/usr/X11R6/share/blackbox/package-menu
fi

# If USE_SUGGESTED_MENU is set and the fifth field is available it will be used.
# Sometimes this is needed, because the console software simply will not
# work or do the right thing running under X.
if [ -z "${USE_SUGGESTED_MENU}" ] ; then
  USE_SUGGESTED_MENU=1
fi

( if [ -d ~/.menus ] ; then
    cat ~/.menus/* 
  fi ;
  if [ -d ${MENU_CONF_DIR} ] ; then
    cat ${MENU_CONF_DIR}/* 
  fi ;
) |
 grep -v '^#' |
 sort -u -t ':' +0 -2 |        # sort on first three fields and no duplicates
 sort -t ':' +1 |              # sort by category
 awk -F ':' -v xterm=${XTERM} -v use_suggested_menu=${USE_SUGGESTED_MENU} '
  {
    if (prevmenu != $2) {
      if (prevmenu) { print "[end]" }
      print "[submenu] ("$2")"
    }
    prevmenu=$2;
    if (use_suggested_menu && $5) {
      sub("XTERM", xterm, $5);
      print "  [exec] ("$1") {"$5"}"
    }
    else {
      if ($3 == "X") print "  [exec] ("$1") {"$4"}"
      else if ($3 == "Console") print "  [exec] ("$1") {"xterm" -e "$4"}"
      else if ($3 == "Window Manger") print "  [restart] ("$1") {"$4"}"
    }
  }
  END { if (prevmenu) { print "[end]" } }' > ${BLACKBOX_MENU_FILE}

if [ $? -ne 0 ] ; then
  echo $0 appeared to have a problem 1>&2
  exit 1
fi

exit 0

