#!/bin/sh
#
#  Copyright (c) 1991, Open Software Foundation, Inc.
#  All Rights Reserved
#
#  Program to add ".so /some/file" to man pages.  This is intended
#  for man pages written in RSML.  If the RSML macros are .so'ed at
#  the beginning of the man pages, the man command will work as is.
#
#  This will either add the .so's in a stream (if you're piping
#  the man files through other programs) or add them to named files.
#  Some basic error checking is done.  For usage see help message.
#
#  J.Bowe  January 1991
# 
# $Header: /project/docsrc/src/dte/RCS/prepend-so.sh,v 1.2 91/03/28 16:35:14 bowe Exp $

# __________________________________________________________________

do_help=false
verbose=false
FILES=""
SOLIST=""

while [ "$#" -gt 0 ]
do
    case $1 in
	-so)		shift; SOLIST="$SOLIST $1" ;;
	-help)		do_help=true		;;
	-v)		verbose=true		;;
	-*)		do_help=true ; break	;;
	*)		FILES="$FILES $1"	;;
    esac
    shift
done

if $do_help ; then
cmd=`basename $0`
cat << H_E_L_P
Usage: $cmd [-so macfile] ... [file] ...
  -so <macfile>	File to ".so" at top of man files.
		There may be several "-so <macfile>" args specified.
		Specify in the order you want them included.
  [file]	Man page file(s) to edit.
  -v 		Show file names as they are processed.
  -help	Show this help message.

$cmd will edit files whose names are give on the command line, or
process input stream (stdin), sending output to stdout.

Examples:
  $cmd -so /local/macros/file1 -so /local/macros/file2 < prog.man > prog.1
  $cmd -so /local/macros/file1 progA.1 progB.1
H_E_L_P
    exit 0
fi

# First, be sure files to .so exist
for so in $SOLIST ; do
    if [ ! -f "$so" ] ; then
	echo "ERROR: File $so does not exist." >&2
	exit 1
    fi
done

if [ -z "$FILES" ] ; then		# reading from stdin

    # output .so lines, then take stdin
    for so in $SOLIST ; do echo ".so $so" ; done
    cat

else					# editing named files

    # First, be sure files to edit exist and are writable
    for f in $FILES ; do
	if [ ! -f "$f" ] ; then
	    echo "ERROR: File $f does not exist." >&2
	    exit 1
	fi
	if [ ! -w "$f" ] ; then
	    echo "ERROR: File $f is NOT writable to you." >&2
	    exit 1
	fi
    done
    # For each man file:
    # output .so lines to tmpfile, cat file to tmpfile, mv tmpfile to man file
    for f in $FILES ; do
	tmp=/tmp/%f.$$
	for so in $SOLIST ; do echo ".so $so" ; done > $tmp
	cat $f >> $tmp
	mv $tmp $f
	if $verbose ; then echo "$f done." >&2 ; fi
    done

fi
