#!/bin/sh
#
# apropos -- search the whatis database for keywords.
#
# Copyright (c) February 1996 Wolfram Schneider <wosch@FreeBSD.org>. Berlin.
# Copyright (c) 1990, 1991, John W. Eaton.
#
# You may distribute under the terms of the GNU General Public
# License as specified in the README file that comes with the man
# distribution.  
#
# John W. Eaton
# jwe@che.utexas.edu
# Department of Chemical Engineering
# The University of Texas at Austin
# Austin, Texas  78712
#
# $FreeBSD: src/gnu/usr.bin/man/apropos/apropos.sh,v 1.14 2001/03/30 10:44:29 wosch Exp $
#
# Japanized by
# Copyright (c) KUMANO, Tadashi <kumano@jp.freebsd.org>, 1996, 1997, 1998,
# Copyright (c) FreeBSD jp-man project <man-jp@jp.freebsd.org>, 1998,
# which is a study toward the multilingual enhancement.
# (version 1.1g 1998/03/28)
# 


PATH=/usr/local/bin:/bin:/usr/bin:$PATH
db=whatis	# name of whatis data base
grepopt=''

# man -k complain if exit_nomatch=1 and no keyword matched
: ${exit_nomatch=0}	
exit_error=2

# argument test
case $# in 0)  
	echo "usage: `basename $0` keyword ..." >&2
	exit $exit_error
	;; 
esac

case "$0" in
	*whatis) grepopt='-w';;	# run as jwhatis(1)
	*)	 grepopt='';;	# otherwise run as japropos(1)
esac

# test manpath
# (JP: use `jmanpath')
# (JP: if manpath is null, use /usr/local/man also)
manpath=`/usr/local/bin/jmanpath -q | tr : '\040'`
case X"$manpath" in X) 
	echo "`basename $0`: manpath is null, use \"/usr/share/man:/usr/local/man\"" >&2
	manpath="/usr/share/man\040/usr/local/man"
	;;
esac


# reset $PAGER if $PAGER is empty
case X"$PAGER" in X) 
	PAGER="jless -s"
	;; 
esac

# (JP: get current LOCALE)
if [ X"$LC_ALL" != X ]
then
	LOCALE="$LC_ALL"
elif [ X"$LC_CTYPE" != X ]
then
	LOCALE="$LC_CTYPE"
elif [ X"$LANG" != X ]
then
	LOCALE="$LANG"
else
	LOCALE=""
fi

#
# search for existing */whatis databases
mandir=''
if [ "$LOCALE" != "" ]
then
	locale_dir="$LOCALE "`echo $LOCALE|sed -n -e 's/^\(.._..\)\..*/\1/p'`" "`echo $LOCALE|sed -n -e 's/^\(..\)_.*/\1/p'`
	for l in $locale_dir
	do
		for d in $manpath
		do
			if [ -f "$d/$l/$db" -a -r "$d/$l/$db" ]
			then
				mandir="$mandir $d/$l/$db"
			fi
		done
	done
fi
for d in $manpath
do
        if [ -f "$d/$db" -a -r "$d/$db" ]
	then
		mandir="$mandir $d/$db"
	fi
done

case X"$mandir" in X)
	echo "`basename $0`: no whatis databases in $manpath" >&2
	exit $exit_error
esac


for manpage
do
	if grep -hi $grepopt -- "$manpage" $mandir; then :
	else
        	echo "$manpage: nothing appropriate"
	fi
done | 

( 	# start $PAGER only if we find a manual page
	while read line
 	do
		case $line in
			# collect error(s)
			*": nothing appropriate") line2="$line2$line\n";;
			# matched line or EOF
			*) break;;
		esac
	done

	# nothing found, exit
	if [ -z "$line" -a ! -z "$line2" ]; then
		printf -- "$line2"
		exit $exit_nomatch
	else
		( printf -- "$line2"; echo "$line"; cat ) | $PAGER
	fi
)
