#!/bin/sh
#
#	catman 1.1 - preformat a manual page tree	Author: Kees J. Bot
#								29 Sep 1995

mandir=/usr/man
bsfilt=
dos=
sections=
verbose=
playact=
junk=
ex=0

while getopts 'M:bdvn' opt
do
	case $opt in
	M)	mandir=$OPTARG
		;;
	b)	bsfilt=yes
		;;
	d)	dos=yes
		;;
	v)	verbose=yes
		;;
	n)	playact=yes
		;;
	?)	echo "Usage: catman [-M directory] [-bdvn] [section ...]" >&2
		exit 1
	esac
done
shift `expr $OPTIND - 1`

# Sections to format.
sections="$*"

member()
{
	# Return true iff a section is part of a section list.
	local section="$1"
	local s

	shift
	test "$#" = 0 && return 0	# Empty section list includes all

	for s
	do
		test "$section" = "$s" && return 0
	done
	return 1
}

if [ "$verbose" ]
then
	tell() { echo "$@" >&2; }
else
	tell() { }
fi

trap 'rm -f "$junk"; exit 1' 1 2 15

cd $mandir || exit
test "$playact" && echo "cd $mandir"
exec < whatis || exit

while read whatis
do
	ifs="$IFS"
	IFS=", "
	set -- $whatis
	page="$1"
	IFS="()"
	set -- $whatis
	section="$2"
	IFS="$ifs"

	member "$section" $sections || continue

	manpage="man$section/$page.$section"
	catpage="cat$section/$page.$section"
	macros=man
	test "$section" = 9 && macros=mnx

	if [ ! -f "$manpage" ]
	then
		# Manual page isn't there?  Complain unless there is a cat page.
		if [ ! -f "$catpage" ]
		then
			echo "catman: $manpage: nonexistent" >&2
		fi
	elif [ ! "$catpage" -newer "$manpage" ]
	then
		# Manual page is newer or never formatted, do so (again).
		tell "formatting: $page($section)"

		if [ ! -d "cat$section" ]
		then
			if [ "$playact" ]
			then
				echo "mkdir cat$section"
			else
				mkdir "cat$section" || exit
			fi
		fi

		cr="
"				# Real carriage return.
		test "$playact" && cr="^M"	# '^' and 'M'.

		input="'$manpage'"
		cmd=

		# Page starts with .\"t to request that tbl be run?
		if read line1 <"$manpage" && \
			test "$line1" : "[.'][ 	]*\\\\\"[ 	]*t[ 	]*$"
		then
			cmd="tbl $input | "
			input=
		fi

		cmd="${cmd}nroff -$macros $input"

		test "$bsfilt" && cmd="$cmd | bsfilt -"

		test "$dos" && cmd="$cmd | sed 's/\$/$cr/'"

		cmd="$cmd >'$catpage'"

		if [ "$playact" ]
		then
			echo "$cmd"
		else
			if eval "$cmd" && test -s "$catpage"
			then
				: fine
			else
				rm -f "$catpage"
				ex=1
			fi
		fi
	else
		# The manual page is already formatted.
		tell "up to date: $page($section)"
	fi
done
exit $ex
