##########################################################################
# Title      :	mkwhatis - make 'whatis'-database from manual pages
# Author     :	Heiner Steven <heiner.steven@odn.de>
# Date       :	1994-03-15
# Requires   :	
# Category   :	System Administration
# SCCS-Id.   :	@(#) mkwhatis	1.2 03/12/19
##########################################################################
# Description
#	Works like 'catman -w', but does not need the manual page
#	sources to create the 'whatis' database
##########################################################################

PN=`basename "$0"`			# program name
VER='1.2'

: ${MANPATH:=/usr/man}
Ext=""					# SCO UNIX: "."

usage () {
    echo >&2 "$PN - create whatis database, $VER (stv '95)
usage: $PN [-M directory]"
    exit 1
}

msg () {
    for i
    do echo "$PN: $i" >&2
    done
}

fatal () { msg "$@"; exit 1; }

while [ $# -gt 0 ]
do
    case "$1" in
	-M)	ManPath="$2"; shift;;
	--)	shift; break;;
	-h)	usage;;
	-*)	usage;;
	*)	break;;			# First file name
    esac
    shift
done

: ${ManPath:=$MANPATH}

[ $# -ne 0 ] && usage

ManDirs=`echo $ManPath | sed 's/:/ /g'`
# SCO Unix: Example of man directories (refer to man(C)):
#	/usr/man/man.C/*
#	/usr/man/cat.C/assign.C.Z
#	/usr/man/cat.C/auths.C.Z
# SunOS:
#	/usr/share/man/man1
#	/usr/share/man/cat1/arch.1

for path in $ManDirs
do
    # Search the whole directory hierarchie
    (cd $path
    for Dir in cat${Ext}*
    do
	# Search section
	Section=`echo $Dir | sed "s/cat${Ext}//"`
	(cd $Dir
	for i in *
	do
	    (case "$i" in
		*.Z)	zcat $i;;
		*.z)	pcat $i;;
		*)	cat $i;;
	    esac) |
	    col -b |				# Steuerzeichen entfernen
	    awk '
	    BEGIN { Blanks = "                              "; }
	    ($1 ~ /^[Nn][Aa][Mm][Ee]/) {	# "Name"-Abschnitt
		getline
		if ( $0 == "" ) getline
		while ( $0 != "" ) {
		    for ( i=1; i<=NF; i++ ) {
			if ( $i == "-" ) {
			    line = line " ('$Section')"
			    printf "%-23s - ", line
			    line = ""
			} else {
			    if ( line == "" )
				line = $i
			    else 
				line = line " " $i
			}
		    }
		    printf "%s ", line
		    line = ""
		    getline
		}
		print ""
		exit 0
	    }'
	done)
    done > whatis)
done
