#!/bin/bash
#
# /usr/lib/windowlab/create_menu.sh
# WindowLab automatic menu generation script.
# This file is invoked by /etc/menu-methods/windowlab.
#
# Copyright (C) 2005 Stan Vasilyev <stan.vasilyev@csun.edu>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# get prefix from command line parameters
prefix=$1
if [ -z "$prefix" ]; then exit 1; fi

# define constants used in this script
global_prefix="/etc/X11/windowlab"
user_menu_file="$prefix/user_menu"
common_menu_file="$global_prefix/common_menu"
debian_config_file="debian_config"
all_menu_file="menudefs.hook"
menufile="$prefix/windowlab.menurc"

# define variables used in windowlab.debianrc file
preferred_browsers=
preferred_email=
preferred_editors=
preferred_graphics=
preferred_terminals=

# include the debian config file, if exists
# if ran as a regular user, includes both global and user configs
for file in "$global_prefix/$debian_config_file" "$prefix/$debian_config_file"
do
	if [ -f "$file" ]
	then
		source "$file"
	fi
done

# backup the menu file
cp -f "$menufile" "$menufile.old"

echo "# This menu file is automatically generated by update-menus, do not edit." > $menufile
echo >> $menufile

# output the Debian menu into Windowlab menu
echo "# Debian Menu:" >> $menufile
for app_list in "$preferred_browsers" "$preferred_email" "$preferred_editors" "$preferred_graphics" "$preferred_terminals"
do
	for app in $app_list
	do
		echo -n "Looking for $app..."
		menu_entry=`grep -m 1 "$app" "$all_menu_file"`
		if [ -n "$menu_entry" ]
		then
			echo "found"
			echo "$menu_entry" >> "$menufile"
			break
		else
			echo "not found"
		fi
	done
done

# output the user menu into Windowlab menu
if [ -f "$user_menu_file" ]
then
	echo >> $menufile
	echo "# User Menu:" >> $menufile
	grep -v "#" "$user_menu_file" | grep ":" >> $menufile
fi

# output the common menu into Windowlab menu
if [ -f "$common_menu_file" ]
then
	echo >> $menufile
	echo "# Common Menu:" >> $menufile
	grep -v "#" "$common_menu_file" | grep ":" >> $menufile
fi

rm -f "$all_menu_file"
