#!/bin/sh 

if [ "$1" == "-h" ]; then
        cat << EOT
menubin - create categorized menu of all programs installed
0.1 (c) 2004-10-20 Tero Karvinen atta iki fi 
url: http://www.iki.fi/karvinen
usage: menubin [<files>|<directories>]
requires: (man bash find) perl
EOT
        exit 0
fi


#CLIBIN="/bin/ /usr/bin/ /usr/local/bin"
UBIN=$1;
CLIBIN="/usr/local/bin /bin /usr/bin";
GUIBIN="/usr/bin/X11";
LIMIT=10;
PMANAGER="dpkg";	# could autodetect wich is bigger, rpm or dpkg database
# libs required by GUI/CLI programs, separated by pipe character |, most important first
GUILIBS="xlibs|libgtk|kdelibs|libgnome|libfox|lesstiff"	
CURSESLIBS="curses"
# it is assumed that all programs have a cli interface

# Distro specific

dpkg_is_gui()	# return "gui", "curses" or "cli" for most complex interface supported by $1
{
	PKG=$1;
	if [[ ! -z `dpkg --print-avail $PKG|grep '^Depends'|grep -E "($GUILIBS)"` ]]; then
		echo "gui";
	elif [[ ! -z `dpkg --print-avail $PKG|grep '^Depends'|grep -E "($CURSESLIBS)"` ]]
		echo "curses";
	else
		echo "cli";
	fi
}

package_info()	# return package manager info of $1. 
{
	case $PMANAGER in 
	"rpm")	echo "Redhat not implemented yet";;
	"dpkg")
		# head part is guessing
		PKG=`dpkg --search $1 |head -1|perl -pe 's/(\w*):.*/$1/'`;
		PSUMMARY=`dpkg --print-avail $PKG |grep -E '^Description'|perl -pe 's/\w*: (.*)/$1/'`
		PUI=`dpkg_is_gui $PKG`;
		;;
	*)
		echo "Error: Unknown system.";
	esac

	echo "\"$PKG\";\"$PSUMMARY\";\"$PUI\"";
}

file_no_path()	# return file part from $1 without path, eg "/bin/ls" -> "ls"
{
	echo $1|perl -pe 's/.*\/(\w*)$/$1/';
}

mancsv() # Return man data on a command $1 as semicolon separated csv. 
{
	whatis $1|perl -pe 's/(\w*)\s*\((\w*)\)\s*-\s*(.*)/"$1";"$2";"$3"/';
}

command_info() # Return all info on command $1 we found
{
	P=$1; # with path
	F=`file_no_path $P`;
	# echo "# $P - $F";
	IMAN=`mancsv $F`;
	IPACK=`package_info $P`;
	echo "$IMAN;$IPACK";
}

# main

I=0;
for P in `find $UBIN $CLIBIN -not -type d`
do
	command_info $P;
	I=$I+1;
	if [[ $I -gt $LIMIT ]]; then
		exit;
	fi
done

# Is it GUI or CLI
# path (X11 -> GUI. What about /usr/bin/?) 
# included dynamic libraries
# package requires X
# only need like 70% success rate
# manual fixing?


