#!/bin/sh
#
# generate_menu for Fluxbox
#
# Copyright (c) 2002 Han Boetes <han@mijncomputer.nl>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
#
# $Id: fluxbox-generate_menu,v 1.38 2003/06/22 12:50:03 fluxgen Exp $

#
# Portability notes:
# To guarantee this script works on all platforms that support fluxbox
# please keep the following restrictions in mind:
#
# don't use [ -e file ] use [ -r file ]
# don't use $(), use ``
# don't use ~, use ${HOME}
# don't use id -u, use whoami
# getopts won't work on all platforms, but the config-file can
# compensate for that.
#


WHOAMI=`whoami`
[ "$WHOAMI" = "root" ] && PATH=/bin:/usr/bin/:/usr/local/bin:/usr/X11R6/bin

# Functions
display_usage() {
    cat <<EOF
Usage: fluxbox-generate_menu [-kgrBh] [-t terminal] [-w url] [-b browser]
         [-m menu-title] [-o /path] [-u /path] [-p /path] [-n /path] [-q /path]
EOF
}

display_help() {
    display_usage
    cat <<EOF

Options:

    -k  Insert a kde menu
    -g  Add a gnome menu
    -B  enable backgroundmenu
    -r  Don't remove empty menu-entries; for templates.

    -t  Favourite terminal
    -w  Homepage for console-browsers. Default is fluxbox.org.
    -b  Favourite browser
    -m  Menu-title; default is "Fluxbox"
    -o  Outputfile; default is ~/.fluxbox/menu
    -u  user sub-menu; default is ~/.fluxbox/usermenu

    -h  Display this help
    -a  Display the authors of this script

  Only for packagers:

    -p  Package-datadir; /usr/local/share
    -n  Gnome-datadir
    -q  KDE-datadir


Files:
    ~/.fluxbux/usermenu     your own submenu which will be included in the menu
    ~/.fluxbox/menuconfig   rc file for fluxbox-generate_menu

EOF
}

display_authors() {
    cat <<EOF

fluxbox-generate_menu was brought to you by:

    Henrik Kinnunen:    Project leader.
    Han Boetes:         Packaging, debugging and scripts.
    Simon Bowden:       Cleanups and compatibility for sun.
    Jeramy B. Smith:    Packaging assistance, gnome and kde menu system.
    Filippo Pappalardo: Italian locales and -t option.
    $WHOAMI:            Innocent bystander.

EOF
}

# ugly code for solaris compat.
case $(uname) in
    Linux|*BSD)
        find_it() {
            which $1 > /dev/null 2>&1 && shift && $*
            }
        ;;
    *)
        find_it() {
            file=`which $1 2> /dev/null`
            if [ -x "$file" ]; then
                if [ $# -gt 1 ]; then
                    shift
                    $*
                fi
                return 0
            else
                return 1
            fi
        }
        ;;
esac

append() {
    echo "      $*" >> ${FILENAME}
}

append_menu() {
    echo "$*" >> ${FILENAME}
}

append_submenu() {
    [ "${REMOVE}" ] && echo >> ${FILENAME} # only an empty line in templates
    append_menu "[submenu] ($1)"
}

append_menu_end() {
    append_menu "[end]"
    [ "${REMOVE}" ] && echo >> ${FILENAME} # only an empty line in templates
}

menu_entry() {
    append "[exec] (`grep -v GenericName $* | grep Name= | cut -d = -f 2`) \
        {`grep -v TryExec $* | grep Exec= | cut -d = -f 2`}"
}

menu_entry_dircheck() {
    if [ -d "$*" ]; then
        menu_entry_dir "$*"
    fi
}

menu_entry_dir() {
    for b in `ls "$*"/*.desktop 2>/dev/null `; do
        menu_entry "${b}"
    done
}

normal_find() {
    while [ "$1" ]; do
        find_it $1     append "[exec]   ($1) {$1}"
        shift
    done
}

clean_up() {
# -e "/^$/d" -e "/^$/d"
cat ${FILENAME} | sed  -e "/^\[submenu]/{
N
/^\[submenu].*\n\[end]/d
}" > ${FILENAME}.tmp
mv -f ${FILENAME}.tmp ${FILENAME}
}

# menu defaults (if translation forget to set one of them)
BACKGROUNDMENU='Backgrounds'
BACKGROUNDMENUTITLE='Set the Background'
BROWSERMENU='Browsers'
CONFIGUREMENU='Configure'
EDITORMENU='Editors'
EXITITEM='Exit'
FBSETTINGSMENU='fluxbox menu'
FILEUTILSMENU='File utils'
GAMESMENU='Games'
GNOMEMENUTEXT='Gnome-menus'
GRAPHICMENU='Graphics'
KDEMENUTEXT='KDE-menus'
MISCMENU='Misc'
MULTIMEDIAMENU='Multimedia'
MUSICMENU='Music'
NETMENU='Net'
OFFICEMENU='Office'
RELOADITEM='Reload config'
RESTARTITEM='Restart'
STYLEMENUTITLE='Choose a style...'
SYSTEMSTYLES='System Styles'
TERMINALMENU='Terminals'
USERSTYLES='User Styles'
VIDEOMENU='Video'
WINDOWMANAGERS='Window Managers'
WORKSPACEMENU='Workspace List'
XUTILSMENU='X-utils'

# Check translation
case ${LC_ALL} in
    ru_RU*) #Russian locales
        #BACKGROUNDMENU='Backgrounds'
        #BACKGROUNDMENUTITLE='Set the Background'
        #FILEUTILSMENU='File utils'
        #OFFICEMENU='Office'
        #SYSTEMSTYLES='�����'
        #USERSTYLES='�����'
        #WINDOWMANAGERS='WindowManagers'
        BROWSERMENU='��������'
        CONFIGUREMENU='���������'
        EDITORMENU='���������'
        EXITITEM='�����'
        FBSETTINGSMENU='FB-���������'
        GNOMEMENUTEXT='Gnome-����'
        GRAPHICMENU='�������'
        KDEMENUTEXT='KDE-����'
        MISCMENU='������'
        MUSICMENU='����'
        NETMENU='����'
        RELOADITEM='�������������'
        RESTARTITEM='�������������'
        STYLEMENUTITLE='�������� �����'
        TERMINALMENU='���������'
        WORKSPACEMENU='������� ������������'
        XUTILSMENU='X-�������'
        ;;
    de_DE*) # german locales
        #WINDOWMANAGERS='Window Managers'
        BACKGROUNDMENU='Hintergrundbilder'
        BACKGROUNDMENUTITLE='Hintergrundbild setzen'
        BROWSERMENU='Internet-Browser'
        CONFIGUREMENU='Einstellungen'
        EDITORMENU='Editoren'
        EXITITEM='Beenden'
        FBSETTINGSMENU='Fluxbox-Einstellungen'
        FILEUTILSMENU='Datei-Utilities'
        GNOMEMENUTEXT='Gnome-Menues'
        GRAPHICMENU='Grafik'
        KDEMENUTEXT='Kde-Menues'
        MISCMENU='Sonstiges'
        MUSICMENU='Musik'
        NETMENU='Netzwerk'
        OFFICEMENU='Bueroprogramme'
        RELOADITEM='Konfiguration neu laden'
        RESTARTITEM='Neustarten'
        STYLEMENUTITLE='Einen Stil auswaehlen...'
        SYSTEMSTYLES='Systemweite Stile'
        TERMINALMENU='Terminals'
        USERSTYLES='Eigene Stile'
        WORKSPACEMENU='Arbeitsflaechenliste'
        XUTILSMENU='X-Anwendungen'
        ;;
    sv_SE*) #Swedish locales
        #BACKGROUNDMENU='Backgrounds'
        #BACKGROUNDMENUTITLE='Set the Background'
        #FILEUTILSMENU='File utils'
        #OFFICEMENU='Office'
        #SYSTEMSTYLES='Stiler'
        #USERSTYLES='Stiler'
        #WINDOWMANAGERS='Window Managers'
        BROWSERMENU='Browsers'
        CONFIGUREMENU='Konfiguration'
        EDITORMENU='Editorer'
        EXITITEM='Exit'
        FBSETTINGSMENU='FB-inst�llningar'
        GNOMEMENUTEXT='Gnome-menyer'
        GRAPHICMENU='Grafik'
        KDEMENUTEXT='KDE-menyer'
        MISCMENU='Blandat'
        MUSICMENU='Musik'
        NETMENU='Net'
        RELOADITEM='Ladda om konfig'
        RESTARTITEM='Starta om'
        STYLEMENUTITLE='V�lj en stil'
        TERMINALMENU='Terminaler'
        WORKSPACEMENU='Arbetsytor'
        XUTILSMENU='X-program'
        ;;
    nl_NL*) #Nederlandse locales
        BACKGROUNDMENU='Achtergrond'
        BACKGROUNDMENUTITLE='Kies een achtergrond'
        BROWSERMENU='Browsers'
        CONFIGUREMENU='Instellingen'
        EDITORMENU='Editors'
        EXITITEM='Afsluiten'
        FBSETTINGSMENU='FB-Instellingen'
        FILEUTILSMENU='Verkenners'
        GNOMEMENUTEXT='Gnome-menu'
        GRAPHICMENU='Grafisch'
        KDEMENUTEXT='KDE-menu'
        MISCMENU='Onregelmatig'
        MUSICMENU='Muziek'
        NETMENU='Net'
        OFFICEMENU='Office'
        RELOADITEM='Vernieuw instellingen'
        RESTARTITEM='Restart'
        STYLEMENUTITLE='Kies een styl'
        SYSTEMSTYLES='Systeem Stylen'
        TERMINALMENU='Terminals'
        USERSTYLES='Gebruikers Stylen'
        WINDOWMANAGERS='Window Managers'
        WORKSPACEMENU='Werkveld Lijst'
        XUTILSMENU='X-utils'
        ;;
    fi_FI*) #Finnish locales
        #BACKGROUNDMENU='Backgrounds'
        #BACKGROUNDMENUTITLE='Set the Background'
        #FILEUTILSMENU='File utils'
        #OFFICEMENU='Office'
        #SYSTEMSTYLES='Tyylit'
        #USERSTYLES='Tyylit'
        #WINDOWMANAGERS='Window Managers'
        BROWSERMENU='Selaimet'
        CONFIGUREMENU='Konfigurointi'
        EDITORMENU='Editorit'
        EXITITEM='Lopeta'
        FBSETTINGSMENU='FB:n Asetukset'
        GNOMEMENUTEXT='Gnomen valikot'
        GRAPHICMENU='Grafiikka'
        KDEMENUTEXT='KDE:n valikot'
        MISCMENU='Sekalaista'
        MUSICMENU='Musikki'
        NETMENU='Verkko'
        RELOADITEM='P�ivit�'
        RESTARTITEM='K�ynnist� uudelleen'
        STYLEMENUTITLE='Valitse tyyli'
        TERMINALMENU='Terminaalit'
        WORKSPACEMENU='Ty�aluet'
        XUTILSMENU='X-Ohjelmat'
        ;;
    ja_JP*) #Japanese locales
        #BACKGROUNDMENU='Backgrounds'
        #BACKGROUNDMENUTITLE='Set the Background'
        #FILEUTILSMENU='File utils'
        #OFFICEMENU='Office'
        #SYSTEMSTYLES='��������'
        #USERSTYLES='��������'
        #WINDOWMANAGERS='Window Managers'
        BROWSERMENU='�֥饦��'
        CONFIGUREMENU='����'
        EDITORMENU='���ǥ���'
        EXITITEM='��λ'
        FBSETTINGSMENU='Fluxbox����'
        GNOMEMENUTEXT='Gnome��˥塼'
        GRAPHICMENU='����'
        KDEMENUTEXT='KDE��˥塼'
        MISCMENU='��������'
        MUSICMENU='����'
        NETMENU='�ͥåȥ��'
        RELOADITEM='���ɤ߹���'
        RESTARTITEM='�Ƶ�ư'
        STYLEMENUTITLE='������������...'
        TERMINALMENU='�����ߥʥ�'
        WORKSPACEMENU='������ڡ���'
        XUTILSMENU='X�桼�ƥ���ƥ�'
        ;;
    fr_FR*) # french locales
        BACKGROUNDMENU="Fond d'�cran"
        BACKGROUNDMENUTITLE="Changer le fond d'�cran"
        BROWSERMENU='Navigateurs'
        CONFIGUREMENU='Configurer'
        EDITORMENU='Editeurs'
        EXITITEM='Sortir'
        FBSETTINGSMENU='Configurer Fluxbox'
        FILEUTILSMENU='Outils fichiers'
        GNOMEMENUTEXT='Menus Gnome'
        GRAPHICMENU='Graphisme'
        KDEMENUTEXT='Menus KDE'
        MISCMENU='Divers'
        MUSICMENU='Musique'
        NETMENU='R�seau'
        OFFICEMENU='Bureautique'
        RELOADITEM='Recharger la configuration'
        RESTARTITEM='Red�marrer Fluxbox'
        STYLEMENUTITLE='Choisir un style...'
        SYSTEMSTYLES='Styles Systeme'
        TERMINALMENU='Terminaux'
        USERSTYLES='Styles Utilisateur'
        WINDOWMANAGERS='Gestionnaires de fen�tres'
        WORKSPACEMENU='Liste des bureaux'
        XUTILSMENU='Outils X'
        ;;
    it_IT*) # italian locales
        #BACKGROUNDMENU='Backgrounds'
        #BACKGROUNDMENUTITLE='Set the Background'
        #FILEUTILSMENU='File utils'
        #OFFICEMENU='Office'
        #SYSTEMSTYLES='Stile'
        #USERSTYLES='Stile'
        #WINDOWMANAGERS='Window Managers'
        BROWSERMENU='Browsers'
        CONFIGUREMENU='Configurazione'
        EDITORMENU='Editori'
        EXITITEM='Esci'
        FBSETTINGSMENU='Preferenze'
        GAMESMENU='Giochi'
        GNOMEMENUTEXT='Gnome'
        GRAPHICMENU='Grafica'
        KDEMENUTEXT='KDE'
        MISCMENU='Varie'
        MUSICMENU='Musica'
        NETMENU='Internet'
        RELOADITEM='Rileggi la configurazione'
        RESTARTITEM='Riavvia'
        STYLEMENUTITLE='Scegli uno stile'
        TERMINALMENU='Terminali'
        WORKSPACEMENU='Aree di lavoro'
        XUTILSMENU='X-utils'
        ;;
    ro_RO*) # Romanian locales
        #FILEUTILSMENU='File utils'
        #OFFICEMENU='Office'
        #RESTARTITEM='Restart'
        #WINDOWMANAGERS='WindowManagers'
        BACKGROUNDMENU='Fundaluri'
        BACKGROUNDMENUTITLE='Alege fundalul'
        BROWSERMENU='Navigatoare'
        CONFIGUREMENU='Configurare'
        EDITORMENU='Editoare'
        EXITITEM='Iesire'
        FBSETTINGSMENU='Meniul Fluxbox'
        GAMESMENU='Jocuri'
        GNOMEMENUTEXT='Meniu Gnome'
        GRAPHICMENU='Grafica'
        KDEMENUTEXT='Meniu KDE'
        MISCMENU='Diverse'
        MULTIMEDIAMENU='Multimedia'
        MUSICMENU='Muzica'
        NETMENU='Net'
        RELOADITEM='Reincarca configuratia'
        STYLEMENUTITLE='Alege un stil...'
        SYSTEMSTYLES='Stiluri sistem'
        TERMINALMENU='Terminale'
        USERSTYLES='Stiluri utilizator'
        WORKSPACEMENU='Lista workspace-uri'
        XUTILSMENU='Utilitare X'
        ;;
    es_ES*) # spanish locales
        #FILEUTILSMENU='File utils'
        #WINDOWMANAGERS='WindowManagers'
        BACKGROUNDMENU='Fondos'
	BACKGROUNDMENUTITLE='Seleccionar Fondo'
	BROWSERMENU='Navegadores'
	CONFIGUREMENU='Configurar'
	EDITORMENU='Editores'
	EXITITEM='Salir'
	FBSETTINGSMENU='Men� fluxbox'
	GAMESMENU='Juegos'
	GNOMEMENUTEXT='Men�s Gnome'
	GRAPHICMENU='Gr�ficos'
	KDEMENUTEXT='Men�s KDE'
	MISCMENU='Varios'
	MULTIMEDIAMENU='Multimedia'
	MUSICMENU='M�sica'
	NETMENU='Red'
	OFFICEMENU='Oficina'
	RELOADITEM='Reconfigurar'
	RESTARTITEM='Reiniciar'
	STYLEMENUTITLE='Escoge un Estilo...'
	SYSTEMSTYLES='Estilos del Sistema'
	TERMINALMENU='Terminales'
	USERSTYLES='Estilos del Usuario'
	WORKSPACEMENU='Lista de Escritorios'
	XUTILSMENU='Utilidades X'
        ;;
    pl_PL*) # Polish locales
        #FILEUTILSMENU='File utils'
        #WINDOWMANAGERS='WindowManagers'
        BACKGROUNDMENU='Tapety'
        BACKGROUNDMENUTITLE='Ustaw tapet?'
        BROWSERMENU='Przegl?darki'
        CONFIGUREMENU='Konfiguracja'
        EDITORMENU='Edytory'
        EXITITEM='Wyj?cie'
        FBSETTINGSMENU='Menu Fluxbox'
        GAMESMENU='Gry'
        GNOMEMENUTEXT='Menu Gnome'
        GRAPHICMENU='Grafika'
        KDEMENUTEXT='Menu KDE'
        MISCMENU='R�?ne'
        MULTIMEDIAMENU='Multimedia'
        MUSICMENU='Muzyka'
        NETMENU='Sie?'
        OFFICEMENU='Aplikacje biurowe'
        RELOADITEM='Od?wie? konfiguracj?'
        RESTARTITEM='Restart'
        STYLEMENUTITLE='Wybierz styl...'
        SYSTEMSTYLES='Style systemowe'
        TERMINALMENU='Terminale'
        USERSTYLES='Style u?ytkownika'
        WORKSPACEMENU='Lista pulpit�w'
        XUTILSMENU='Narz?dzia X'
        ;;
    *)
        ;;
esac

# Set Defaults
FILENAME="${FILENAME:=${HOME}/.fluxbox/menu}"
MENUTITLE="${MENUTITLE:=Fluxbox}"
HOMEPAGE="${HOMEPAGE:=fluxbox.org}"
USERMENU="${USERMENU:=${HOME}/.fluxbox/usermenu}"

# Read the menuconfig file if it exists or else create it.
# But not during install time, use envvar for sun
if [ ! "${INSTALL}" = "Yes" ];then
    if [ -r ${HOME}/.fluxbox/menuconfig ]; then
        . ${HOME}/.fluxbox/menuconfig
    else
        if [ ! "$WHOAMI" = root ]; then # this is only for users.
            if touch ${HOME}/.fluxbox/menuconfig; then
                cat<<EOF> ${HOME}/.fluxbox/menuconfig
# This file is read by fluxbox-generate_menu.  If you don't like a
# default you can change it here.  Don't forget to remove the # in front
# of the line.

# Your favourite terminal
# MY_TERM=aterm

# Your favourite browser
# MY_BROWSER=mozilla

# Name of the outputfile
# FILENAME=${HOME}/.fluxbox/menu

# MENUTITLE=\`fluxbox -version|cut -d " " -f-2\`

# standard url for console-browsers
# HOMEPAGE=fluxbox.org

# location with your own menu-entries
# USERMENU=~/.fluxbox/usermenu

# --- Datadirs
# These are datadirs; So if fluxbox data is installed in
#   /usr/share/fluxbox
# your datadir is: /usr/share

# Data-dir
# PKGDATADIR=/usr/share

# Gnome data-dir
# in case gnome is installed in another datadir.
# GPKGDATADIR=/opt/gnome/share

# Kde data-dir
# KPKGDATADIR=/opt/kde/share

# Sepparate the list of background-dirs with semicolumns ':'
# BACKGROUND_DIRS="${HOME}/.fluxbox/backgrounds/:/usr/local/share/fluxbox/backgrounds/:/usr/share/wallpapers"

# --- Boolean variables.
# Setting a variable to ``no'' won't help. Comment them out if you don't
# want them.  Setting are overruled by the command-line options.

# Include all backgrounds in your backgrounds-directory
# BACKGROUNDMENUITEM=yes

# Include kde-menus
# KDEMENU=yes

# Include gnome-menus
# GNOMEMENU=yes

# Don't cleanup the menu
# REMOVE=no

EOF
            else
                echo "Warning: I could't create ${HOME}/.fluxbox/menuconfig" >&2
            fi
        fi
    fi
fi
# Get options.
while getopts ":Bkhragb:t:p:w:u:n:q:o:m:-:" COMMAND_LINE_ARGUMENT ; do
   case "${COMMAND_LINE_ARGUMENT}" in
       B) BACKGROUNDMENUITEM=yes ;;
       k) KDEMENU=yes ;;
       g) GNOMEMENU=yes ;;
       t) MY_TERM=${OPTARG} ;;
       b) MY_BROWSER=${OPTARG} ;;
       o) FILENAME=${OPTARG} ;;
       p) PKGDATADIR=${OPTARG} ;;
       n) GPKGDATADIR=${OPTARG} ;;
       q) KPKGDATADIR=${OPTARG} ;;
       m) MENUTITLE=${OPTARG} ;;
       w) HOMEPAGE=${OPTARG} ;;
       u) USERMENU=${OPTARG} ;;
       r) REMOVE=no ;;
       h) display_help ; exit 0 ;;
       a) display_authors ; exit 0 ;;
       -) echo "fluxbox-generate_menu doesn't recognize -- gnu-longopts."
          echo 'Use fluxbox-generate_menu -h for a long help message.'
          display_usage
          exit 1 ;;
       *) echo 'Use fluxbox-generate_menu -h for a long help message.'
          display_usage
          exit 1 ;;
   esac
done
# Check defaults

# Can we actually create ${FILENAME}
touch ${FILENAME} 2> /dev/null
if [ $? -ne 0 ]; then
    echo "Fatal error: can't create $FILENAME" >&2
    exit 1
fi

# backup menu
if [ -w "${FILENAME}" ]; then
    if [ -f ${FILENAME}.firstbak ]; then
        cp ${FILENAME} ${FILENAME}.firstbak
    fi
    mv ${FILENAME} ${FILENAME}.bak
fi

# packagedatadir
PREFIX="${PREFIX:=@PREFIX@}"
if [ ! -d "${PKGDATADIR}" -o -z "${PKGDATADIR}" ]; then
    if [ "$PREFIX" = '@PREFIX@' ]; then
        PKGDATADIR=/usr/local/share
    else
        PKGDATADIR=${PREFIX}/share
    fi
fi

# gnome packagedatadir
if [ ! -d "${GPKGDATADIR}" -o -z "${GPKGDATADIR}" ]; then
    GPKGDATADIR=${PKGDATADIR}
fi

# kde packagedatadir
if [ ! -d "${KPKGDATADIR}" -o -z "${KPKGDATADIR}" ]; then
    KPKGDATADIR=${PKGDATADIR}
fi

# directory for the backgrounds
if [ -z "$BACKGROUND_DIRS" ]; then
    BACKGROUND_DIRS="${HOME}/.fluxbox/backgrounds/:${PKGDATADIR}/fluxbox/backgrounds/"
fi

# find the default terminal
find_it $MY_TERM
if [ $? -ne 0 ]; then
    [ -n "$MY_TERM" ] && echo "Warning: you chose an invalid term." >&2
    #The precise order is up for debate.
    for term in Eterm aterm rxvt wterm xterm konsole gnome-terminal; do
        if find_it $term; then
            DEFAULT_TERM=$term
            break
        fi
    done
else
    DEFAULT_TERM=$MY_TERM
fi


# find the default browser
find_it $MY_BROWSER
if [ $? -ne 0 ]; then
    [ -n "$MY_BROWSER" ] && echo "Warning: you chose an invalid browser." >&2
    #The precise order is up for debate.
    for browser in MozillaFirebird firebird opera skipstone phoenix mozilla galeon konqueror dillo netscape links w3m lynx; do
        if find_it $browser; then
            DEFAULT_BROWSER=$browser
            break
        fi
    done
else
    DEFAULT_BROWSER=$MY_BROWSER
fi


# a unix system without any terms. that's odd
if [ -z "$DEFAULT_TERM" ]; then
    cat <<EOF>&2
Warning: I can't find any terminal-emulators in your PATH.
Please fix your PATH or specify your favourite terminal with the -t option
EOF
fi


# Start of menu
cat << EOF > ${FILENAME}
# Generated by fluxbox-generate_menu
#
# If you read this it means you want to edit this file manually, so here
# are some useful tips:
#
# - You can add your own menu-entries to ~/.fluxbox/usermenu
#
# - If you miss apps please let me know and I will add them for the next
#   release.
#
# - The -r option prevents removing of empty menu entries and lines which 
#   makes things much more readable.
#
# - To prevent any other app from overwriting your menu
#   you can change the menu name in .fluxbox/init to:
#     session.menuFile: /home/you/.fluxbox/my-menu

EOF

echo "[begin] (${MENUTITLE})" >> ${FILENAME}


append "[exec]    (${DEFAULT_TERM}) {${DEFAULT_TERM}}"

case "$DEFAULT_BROWSER" in
    links|w3m|lynx)  append "[exec] (${DEFAULT_BROWSER}) {${DEFAULT_TERM} -e ${DEFAULT_BROWSER} ${HOMEPAGE}}" ;;
    firebird|mozilla|phoenix|galeon|dillo|netscape) append "[exec] (${DEFAULT_BROWSER}) {${DEFAULT_BROWSER}}" ;;
    konqueror) append "[exec] (konqueror) {kfmclient openProfile webbrowsing}" ;;
    opera) append "[exec] (opera) {env QT_XFT=true opera}" ;;
    MozillaFirebird) append "[exec] (firebird) {MozillaFirebird}" ;;
    *) append "[exec] (`basename $DEFAULT_BROWSER`) {$DEFAULT_BROWSER}" ;;
esac

find_it fbrun           append "[exec]   (Run) {fbrun}"


append_submenu "${TERMINALMENU}"
    normal_find xterm gnome-terminal Eterm konsole aterm rxvt
append_menu_end


append_submenu "${NETMENU}"
    append_submenu "${BROWSERMENU}"
        normal_find netscape galeon mozilla dillo
        find_it opera       append "[exec]   (opera) {env QT_XFT=true opera}"
        find_it konqueror   append "[exec]   (konqueror) {kfmclient openProfile webbrowsing}"
        find_it links       append "[exec]   (links) {${DEFAULT_TERM} -e links ${HOMEPAGE}}"
        find_it w3m         append "[exec]   (w3m) {${DEFAULT_TERM} -e w3m ${HOMEPAGE}}"
        find_it lynx        append "[exec]   (lynx) {${DEFAULT_TERM} -e lynx ${HOMEPAGE}}"
    append_menu_end

    append_submenu IM
        normal_find gaim kopete gnomemeeting
        find_it licq        append "[exec]   (licq) {env QT_XFT=true licq}"
    append_menu_end

    append_submenu Mail
        normal_find sylpheed kmail evolution
        find_it mutt        append "[exec]   (mutt) {${DEFAULT_TERM} -e mutt}"
    append_menu_end

    append_submenu IRC
        normal_find xchat ksirc
        find_it irssi       append "[exec]   (irssi) {${DEFAULT_TERM} -e irssi}"
        find_it BitchX      append "[exec]   (BitchX) {${DEFAULT_TERM} -e BitchX -N}" || \
          find_it bitchx    append "[exec]   (BitchX) {${DEFAULT_TERM} -e bitchx -N}"
        find_it ircii       append "[exec]   (ircii) {${DEFAULT_TERM} -e ircii -s}"
    append_menu_end

    append_submenu P2P
        normal_find gtk-gnutella lopster
    append_menu_end

    normal_find gftp pan

append_menu_end


append_submenu "${EDITORMENU}"
    normal_find nedit gvim xemacs emacs gedit xedit kword kwrite kate
append_menu_end

append_submenu "${FILEUTILSMENU}"
    normal_find konqueror
    find_it     nautilus append "[exec] (nautilus) {nautilus --no-desktop}"
    find_it     mc append "[exec]   (mc) {${DEFAULT_TERM} -e mc}"
append_menu_end

append_submenu "${MULTIMEDIAMENU}"
       append_submenu "${GRAPHICMENU}"
               normal_find gimp xv gqview xpaint kpaint kiconedit xscreensaver-demo blender
               find_it gears            append "[exec] (Mesa gears) {gears}"
               find_it morph3d          append "[exec] (Mesa morph) {morph3d}"
               find_it reflect          append "[exec] (Mesa reflect) {reflect}"
       append_menu_end

       append_submenu "${MUSICMENU}"
               normal_find xmms noatun alsaplayer gqmpeg aumix xmixer gmix kmix grecord \
                   kmidi xplaycd soundtracker grip easytag audacity zinf rhythmbox
               find_it cdcd        append "[exec] (cdcd) {${DEFAULT_TERM} -e cdcd}"
               find_it cplay       append "[exec] (cplay) {${DEFAULT_TERM} -e cplay}"
               find_it alsamixer   append "[exec] (AlsaMixer) {${DEFAULT_TERM} -e alsamixer}"
       append_menu_end


       append_submenu "${VIDEOMENU}"
           normal_find xine aviplay gtv gmplayer xmovie xcdroast xgdb ddd realplay xawtv
           find_it dvdrip append "[exec] (dvdrip) {nohup dvdrip}"
       append_menu_end

       append_submenu "${XUTILSMENU}"
           normal_find xfontsel xman xload xfigxbiff editres viewres xclock xmag wmagnify gkrellm
       append_menu_end
append_menu_end


append_submenu "${OFFICEMENU}"
    normal_find xclock xcalc kcalc
    find_it gcalc           append "[exec] (gcalc) {gcalc}" || \
        find_it gnome-calculator append "[exec] (gcalc) {gnome-calculator}"
    find_it ooffice append "[exec] (Open Office) {ooffice}"
    find_it oocalc append "[exec] (OO Calc) {oocalc}"
    find_it oowriter append "[exec] (OO Writer) {oowriter}"
    find_it ooimpress append "[exec] (OO Impress) {ooimpress}"
    find_it oodraw append "[exec] (OO Draw) {oodraw}"
    find_it oomath append "[exec] (OO Math) {oomath}"
    find_it oopadmin append "[exec] (OO Printer Administration) {oopadmin}"
    find_it mrproject append "[exec] (Mr.Project) {mrproject}"
    find_it soffice append "[exec] (Star Office) {soffice}"

    normal_find abiword kword wordperfect katoob acroread xpdf
append_menu_end

append_submenu "${GAMESMENU}"
    normal_find bzflag gnibbles gnobots2 tuxpuck gataxx glines \
        gnect mahjongg gnomine gnome-stones gnometris gnotravex \
        gnotski iagno knights eboard xboard freecell pysol \
        gtali tuxracer xpenguins xsnow xeyes xpenguins \
        quake2 quake3 skoosh same-gnome enigma xbill
        find_it et append "[exec] (Enemy Territory) {et}"
append_menu_end

# gnome menu
if [ -d ${GPKGDATADIR}/gnome/apps -a "${GNOMEMENU}" ]; then
    append_submenu "${GNOMEMENUTEXT}"
    for a in `ls ${GPKGDATADIR}/gnome/apps/` ; do
        if [ -d ${GPKGDATADIR}/gnome/apps/"${a}" ]; then
            append_submenu "${a}"
            menu_entry_dir "${GPKGDATADIR}/gnome/apps/${a}"
            menu_entry_dircheck "/etc/X11/applnk/${a}"
            append_menu_end
        fi
    done
    append_menu_end
fi

# kde submenu
if [ -d ${KPKGDATADIR}/applnk/ -a "${KDEMENU}" ]; then
    append_submenu "${KDEMENUTEXT}"
    for a in `ls ${KPKGDATADIR}/applnk/` ; do
        if [ -d ${KPKGDATADIR}/applnk/"${a}" ]; then
            append_submenu "${a}"
            for x in ${KPKGDATADIR}/applnk/"${a}"/*; do
                if [ -d ${KPKGDATADIR}/applnk/"${a}"/"${x}" ]; then
                    append_submenu "${x}"
                    menu_entry_dir ${KPKGDATADIR}/applnk/"${a}"/"${x}"
                    append_menu_end
                fi
            done
            menu_entry_dir ${KPKGDATADIR}/applnk/"${a}"
            append_menu_end
        fi
    done
    menu_entry_dir ${KPKGDATADIR}/applnk/
    append_menu_end
fi

#User menu
if [ -r "${USERMENU}" ]; then
    cat ${USERMENU} >> ${FILENAME}
fi

append_submenu "${FBSETTINGSMENU}"
    append "[config] (${CONFIGUREMENU})"

    append_menu "[submenu] (${SYSTEMSTYLES}) {${STYLEMENUTITLE}}"
        append "[stylesdir] (${PKGDATADIR}/fluxbox/styles)"
    append_menu_end

    append_menu "[submenu] (${USERSTYLES}) {${STYLEMENUTITLE}}"
        append "[stylesdir] (~/.fluxbox/styles)"
    append_menu_end

    # Backgroundmenu
    addbackground() {
                picturename=`basename "$1"`
                append "[exec] (${picturename%.???}) {fbsetbg -f \"$1\" }"
    }

    if [ "$BACKGROUNDMENUITEM" = "yes" ]; then
        IFS=: # set delimetor for find
        NUMBER_OF_BACKGROUNDS=`find $BACKGROUND_DIRS -follow -type f 2>/dev/null|wc -l`
        if [ "$NUMBER_OF_BACKGROUNDS" -gt 0 ]; then
            append_menu "[submenu] (${BACKGROUNDMENU}) {${BACKGROUNDMENUTITLE}}"
            if [ "$NUMBER_OF_BACKGROUNDS" -gt 30 ]; then
                menucounter=1 ; counter=1
                append_menu "[submenu] (${BACKGROUNDMENU} $menucounter) {${BACKGROUNDMENUTITLE}}"
                find $BACKGROUND_DIRS -follow -type f|sort|while read i; do
                    counter=`expr $counter + 1`
                    if [ $counter -eq 30 ]; then
                        counter=1
                        menucounter=`expr $menucounter + 1`
                        append_menu_end
                        append_menu "[submenu] (${BACKGROUNDMENU} $menucounter) {${BACKGROUNDMENUTITLE}}"
                    fi
                    addbackground "$i"
                done
                append_menu_end
            else
                find $BACKGROUND_DIRS -follow -type f|sort|while read i; do
                addbackground "$i"
                done
            fi
            append_menu_end
        else
            echo "Warning: You wanted a background-menu but I couldn't find any backgrounds in:
    $BACKGROUND_DIRS" >&2
        fi
    fi

    append "[workspaces]   (${WORKSPACEMENU})"

    append_submenu Tools
        normal_find fluxconf fluxkeys fluxmenu
        # if gxmessage exitst use it; else use xmessage
        find_it gxmessage append \
          "[exec] (Windowname) {xprop WM_CLASS|cut -d \\\" -f 2|gxmessage -file - -center}" || \
            find_it xmessage append \
              "[exec] (Windowname) {xprop WM_CLASS|cut -d \\\" -f 2|xmessage -file - -center}"
        find_it import append "[exec] (screenshot) {import screenshot.png && qiv -W 50 screenshot.png}"
        find_it fbrun append "[exec] (Run) {fbrun}"
        find_it fluxbox-generate_menu append "[exec] (regenerate menu) {fluxbox-generate_menu}"
    append_menu_end

    append_submenu ${WINDOWMANAGERS}
        find_it starticewm append "[restart] (icewm) {starticewm}" ||\
            find_it icewm append "[restart] (icewm) {icewm}"
        find_it ion append "[restart] (ion) {ion}"
        find_it startkde append "[restart] (kde) {startkde}"
        find_it startsawfish append "[restart] (sawfish) {startsawfish}" ||\
            find_it sawfish append "[restart] (sawfish) {sawfish}"
        find_it startgnome append "[restart] (gnome) {startgnome}" ||\
            find_it gnome-session append "[restart] (gnome) {gnome-session}"
        find_it startwindowmaker append "[restart] (windowmaker) {startwindowmaker}" ||\
            find_it wmaker append "[restart] (windowmaker) {wmaker}"
        find_it startenlightenment append "[restart] (enlightenment) {startenlightenment}" ||\
            find_it enlightenment append "[restart] (enlightenment) {enlightenment}"
        find_it startafterstep append "[restart] (afterstep) {startafterstep}" ||\
            find_it afterstep append "[restart] (afterstep) {afterstep}"
        find_it startopenbox append "[restart] (openbox) {startopenbox}" ||\
            find_it openbox append "[restart] (openbox) {openbox}"
        find_it startevilwm append "[restart] (evilwm) {startevilwm}" ||\
            find_it evilwm append "[restart] (evilwm) {evilwm}"
        find_it startwaimea append "[restart] (waimea) {startwaimea}" ||\
            find_it waimea append "[restart] (waimea) {waimea}"
        find_it startxfce append "[restart] (xfce) {startxfce}"
        find_it startpekwm append "[restart] (pekwm) {startpekwm}" ||\
            find_it pekwm append "[restart] (pekwm) {pekwm}"
    append_menu_end

    append "[reconfig] (${RELOADITEM})"
    append "[restart] (${RESTARTITEM})"
    append "[exit] (${EXITITEM})"

    append_menu_end
append_menu_end

# this function removes empty menu items. It can not yet  remove  nested
# empty submenus :\

if [ ! "${REMOVE}" ]; then
    clean_up
fi

echo 'Menu succesfully generated.'
echo 'Use fluxbox-generate_menu -h to read all about the latest features.'