#!/bin/sh
:
: man
:
#	@(#)Copyright Apple Computer 1987	Version 1.7 of man.sh on 91/12/16 20:04:46 (ATT 1.1)
#	Catable manual entries printer
#

BASE=/usr
PATH=/bin:/usr/bin:/usr/ucb
LESS="/usr/local/bin/less"
GZCAT="/usr/local/bin/gzcat"

sec=\?
dir=
col=
cmd=
entries=
TTERM=
mypager=

#  parse options

for i in $*
do case $i in

	[1-8])	sec=$i ;;
	-c)	col=col ;;
	-d)	dir=. ;;
	-w)	cmd=w ;;
	-T*)	TERM="`echo $i | sed 's/-T//'`" ;;
	-12)	TTERM=-12 ;;
	*)	entries="$entries $i" ;;
   esac
done

if [ "$TERM" = "lpr" ]
then
	PAGER=pg
fi
if [ "$TERM" = "lp" ]
then
	PAGER=pg
fi

if [ "$PAGER" = "" ]
then
	mypager="$LESS -s -M -e"
else
	# pages such as pg need to have ul handle underlining
	mypager="ul | $PAGER"
fi

if [ ! -t 1 ] ; then	# If stdout is not a tty skip the pager
	mypager=cat
fi



#  now find the named entries

# Only need to truncate to 14 chars for System V file system.
# / is now a Berkeley file system, so we only truncate when we
# are not can't find the requested file.

for i in $entries; do

    if [ "$dir" = "." ]; then
	if [ ! -r "$i" ]; then
	    ti=`expr $i : '^\(..............\).*' '|' $i`
	    if [ ! -r "$ti" ]; then
		echo $0: $i not found >&2
		exit 1
	    else
		all="$all $ti"
	    fi
	else 
	    all="$all $i"
	fi

    else
	cd $BASE/catman
	fil="`find */man$sec/$i.* -print 2>/dev/null`"
	if [ -n "$fil" ]; then
	    all="$all $fil"
	else
	    fil="`find */man$sec/$i -print 2>/dev/null`"
	    if [ -n "$fil" ]; then
		all="$all $fil"
	    else
		ti=`expr $i : '^\(..............\).*' '|' $i`
		fil="`find */man$sec/$ti -print 2>/dev/null`"
		if [ -n "$fil" ]; then
		    all="$all $fil"
		else
		    echo $0: $i not found >&2
		    exit 1
		fi
	    fi
	fi
    fi
done


# fix up the terminal type option (make sure to use col, etc.)

case "$TERM$TTERM" in

	300|300s|450|37|300-12|300s-12|450-12| \
		4000a|4000A|382|1620|1620-12)	post="greek -T$TERM$TTERM" ;;
	hp|2621|2645|2640)	col=col; post="greek -T$TERM$TTERM" ;;
	4014|tek)	post="greek -T$TERM$TTERM" ;;
	X97)		col=col; post=xerox ;;
	*)		col=col; post=cat ;;
esac

if [ "$col" != "" ]
   then post="$col | $post"
fi


# now print the pages
export TERM

if [ "$cmd" = "w" ]

   then	echo $all
	exit 0

   else	for i in $all

	do
	   eval "$GZCAT -f $i | $post | $mypager"
	done

fi
