#!/bin/ksh -x
# Convert SGML man files in some directory to text man pages

# This script generates another script (in /tmp), and then executes that script.
# The script generated is known as the converter. It is generated
# (largely) by processing the output of catman(1m) - a unix utility
# that converts provides instructions on how to convert man pages to
# text format

# The instructions catman produces are "noisy", and cannot be directly
# executed, so we clean those instructions to form a shell script.

# In addition, the text man pages produced by that set of instructions
# leaves all the headers and footers in, so we clean these pages
# further to delete these extraneous headers and footers.

# The name of the shell script we generate - this does all the work.
converter=/tmp/convert.$$

# function that builds the first part of the converter script which
# provides the text man page cleaning functionality

# Note the cd that we do here - needed when this script is executed
# with a relative path, as opposed to an absolute path

construct_convert_header(){

if [ "$1" = "" ]; then 
  currentdir=$(pwd)
else
  currentdir=$1
fi

echo '#!/bin/ksh'
cat <<EOF
clean_man_pages(){
( cd $currentdir
col -xb |
awk -f $(dirname $0)/s2.awk |
sed -f $(dirname $0)/s3.sed |
awk -f $(dirname $0)/s4.awk |
awk -f $(dirname $0)/s5.awk 
)
}
EOF
}

# The parent directory of both the input SGML files, and the output text man pages.
# The SGML files are in subdirectories, labelled man[0-9] - the output text man
# pages will be in subdirectories cat[0-9]
if [ "$1" = "" ]; then 
    mandir=$(dirname $0)/../../sman
else
    mandir=$1/sman
fi





# The sed script which cleans up the instructions produced by catman
clean_instructions=$(dirname $0)/clean.sed


#trap "rm -f /tmp/sman_* /tmp/*.$$" EXIT INT QUIT KILL USR1 USR2
trap "rm -f /tmp/sman_* " EXIT INT QUIT KILL USR1 USR2
rm -f $mandir/cat*/*.*
construct_convert_header >$converter && # construct header of converter script
catman -p -n -M ${mandir:?} | # then use catman(1) to tell us what to do
sed -f ${clean_instructions} >> $converter && # then clean up its output to be
				# more efficient and effective 
chmod +x $converter # then change the resulting script to make it
		    # executable 
$converter # and execute it

