#!/bin/bash

##==============================================================================
#$ MPAGE      - Generic MPage based filter script              Updated: 03/21/01
##------------------------------------------------------------------------------
##
## OPTIONS RECOGNIZED: ( all must be preceded by a "-" )                 
##                                                                       
## Page Orientation: (Default portrait)	                                 
##       -orientation= 'portrait' or 'landscape'                       
##                                                                       
## Horizontal Pitch Selection                                            
##       -pitch=       numeric cpi value                  
##       -point=       numeric cpi value                  
##                                                                       
## Vertical Pitch Selection                                              
##       -lpi=         numeric lines per inch setting                  
##       -vsi=         Vertical Space Increment # in 1/48's of an inch 
##                                                                       
## Page Layout Selection                                                 
##	-lpp=	       set text length of page to nnn lines             
##                                                                       
## Any valid mpage command line argument                                 
##                                                                       
##==============================================================================

# The basic way this script works is that it parses for our standard
# command line arguments and stores those values in some variables.  Any
# arguments that aren't our standard ones are kept and assumed to already
# be Mpage arguments.  Then, we look at the values we parsed out and convert
# those to Mpage arguments.  Once that is done, we route STDIN through
# Mpage giving Mpage the modified list of arguments then then the formatted
# output from Mpage appears on our STDOUT.  We are basically just translating
# out standard command line arguments into Mpage command line switches and
# then using Mpage to format the report.

# set up redirection of stderr

if [ -z "$LOGFILE" ]
then
    UMASK=`umask`; umask 00             # save and set the umask
    log=/tmp/MPAGE_filter.last
    rm -rf $log
    echo "" > $log
    umask $UMASK                        # restore original umask                
else
    log=$LOGFILE
fi

exec 2>>$log

# do some logging

echo "" >> $log
echo "==========[ Starting filter ]================================================" >> $log
echo "`grep ^[#][$] $0|cut -b4-`" >> $log
echo "=============================================================================" >> $log
echo "" >> $log
echo "Filter Script Pathname: $0" >> $log
echo "Command line arguments: $*" >> $log
echo "" >> $log

# Initialize option variables to default values

orientation="def"
pagelen="def"
pitch="def"
lpi="def"
vsi="def"
font="def"
collate="def"
pagesPerSheet="def"

# set up some defaults

defaultPortPitch="10"
defaultLandPitch="12"

defaultPortLpp="60"
defaultLandLpp="60"

defaultPortLpi="6"
defaultLandLpi="8"

#
# Can we find the mpage program?
#

if [ -z "`type mpage 2>/dev/null`" ]
then
    echo "*** Error, 'mpage' is not installed or in the current PATH!" >> $log
    echo "==========[ Exiting filter ]================================================" >> $log
    exit 1
fi

#
# Determine which options have been invoked
#

count=$#

while [ $count -gt 0 ]
do
    case "$1" in

        #
        # Help
        #
        -[?]|--help)
                grep ^[#][#$] $0|cut -b3-
                exit 0
                ;;

        #
        # Version
        #
        --version)
                grep ^[#][$] $0|cut -b4-
                exit 0
                ;;

        #
        # Revision History
        #
        --history)
                grep ^[#][+] $0|cut -b4-
                exit 0
                ;;
	# 
	# Check for Page Orientation
	#
	-orientation=*) # select landscape orientation
	        orientation=`echo $1 | cut -f 2 -d = | tr '[A-Z]' '[a-z]'`
                ;;

        # 
        # Check for Pitch in Characters Per Inch
        #
        -pitch=* | -point=* | -cpi=*)
	        pitch=`echo $1 | cut -f 2 -d =`
                ;;

        #
        # Check for vertical line spacing
        #
	-lpi=*)	# lines per inch
	        lpi=`echo $1 | cut -f 2 -d =`
                vsi="def"
                pagelen="def"
                ;;
	-vsi=*)	# 1/48th's of an inchs
	        vsi=`echo $1 | cut -f 2 -d =`
                lpi="def"
                pagelen="def"
                ;;

        #
        # Check page layout settings
        #
	-lpp=*) # text lines per page	
		pagelen=`echo $1 | cut -f 2 -d =`
                lpi="def"
                vsi="def"
                ;;

	# 
	# Check for Font Names
	#
	-font=*) # select font
	        font=`echo $1 | cut -f 2 -d =`
                ;;

	# 
	# Check for Collate
	#
	-collate) # select collate
	        collate="true"
                ;;

        #
        # Mpage arguments that we need to check for
        #
        -[1248])  # MPage Pagees Per Sheet so we can default the Draw Border option
                  pagesPerSheet=`echo $1 | cut -b2-`
                  ;;


        #
        # Catch any other left over arguments.  We will send them to Mpage pater.
        #
	*)        #catch any non-processed arguments
                  args="$args $1"
                  ;;
    esac
    
    shift
    count=$(($count - 1))
done

echo "Current settings to use when formatting, "def" means Default." >> $log
echo "    Orientation: $orientation"   >> $log
echo "            Lpp: $pagelen"       >> $log
echo "          Pitch: $pitch"         >> $log
echo "            Lpi: $lpi"           >> $log
echo "            Vsi: $vsi"           >> $log
echo "           Font: $font"          >> $log
echo "        Collate: $collate"       >> $log
echo "    Pages/Sheet: $pagesPerSheet" >> $log
echo "Extra Arguments: $args"          >> $log
echo ""                                >> $log

#
# Now convert the arguments into MPAGE arguments
#

arglist=""

#
# How many pages per sheet should we print?
#

case "$pagesPerSheet" in
    def) arglist="$arglist -1 -o"
         ;;
    *)   arglist="$arglist -$pagesPerSheet"
         ;;
esac

#
# Do we need to set up for an explicit ORIENTATION setting?
#

case "$orientation" in
    def)    # Do nothing if the field was not set on the command line
            ;;

    port*)  # If explicitly set to Portrait, we want to default the
            # page LPI and CPI settings to a standard set of values

            if [ "$pagelen" = "def" -a "$lpi" = "def" ]
            then
                pagelen="$defaultPortLpp"
            fi

            if [ "$pitch" = "def" ]
            then
                pitch="$defaultPortPitch"
            fi
            ;;
     
    land*)  # If explicitly set to Landscape, we need to set the Mpage 
            # landscape option and we also want to default the 
            # page LPI and CPI settings to a standard set of values

            arglist="$arglist -l"

            if [ "$pagelen" = "def" -a "$lpi" = "def" ]
            then
                pagelen="$defaultLandLpp"
            fi

            if [ "$pitch" = "def" ]
            then
                pitch="$defaultLandPitch"
            fi
            ;;
esac

#
# Did we get a request for a custom CPI pitch setting?
#

case "$pitch" in 
    def)    # Do nothing if the field was not set on the command line
            ;;

    *)      # Calculate the requested pitch setting.  Mpage does not support
            # directly setting a pitch.  Instead, it accepts a setting for
            # the maximum number of columns you want to fit on the page.  So,
            # we look at how the report will print on the page (port or land)
            # and based on that, we figure out how many columns will fit. For
            # this calculation, we assume a page size of 8 by 11 inches. This
            # is what you would get with an 80 column report printed at 10
            # pitch in portrait mode and a 132 column report printed at 12
            # pitch in landscape mode.

            case "$orientation" in
               def|port*) arglist="$arglist -W$((8  * $pitch))"
                          ;;
               land*)     arglist="$arglist -W$((11 * $pitch))"
                          ;;
            esac
            ;;
esac

#
# Did we get a request for a custom Lines Per Inch setting?
#

case "$lpi" in
    def)    # Do nothing if the field was not set on the command line
            ;;

    *)      # Calculate the requested Lines Per Inch. Mpage does not support
            # directly setting LPI.  Instead, it accepts a setting for the
            # maximum number of lines you want to fit on the page.  So, we
            # look at how the report will print on the page (port or land)
            # and based on that, we figure out how many rows will fit. For
            # this calculation, we assume a page size of 7.5 by 10 inches. 
            # This is what you would get with a 60 line report printed at 6 
            # lpiin portrait mode and a 60 line report printed at 8 lpi in 
            # landscape mode.  Since the shell can't handle non integer
            # math, for the 7.5, we calc with 75 and then devide the result
            # by 10 to maintain precision.

          case "$orientation" in
              def|port*) arglist="$arglist -L$(( 10 * $lpi      ))"
                         ;;
              land*)     arglist="$arglist -L$(( 75 * $lpi / 10 ))"
                         ;;
          esac
          ;;
esac

#
# Did we get a request for a custom Vertical Spacing Increment?
#

case "$vsi" in
    def)    # Do nothing if the field was not set on the command line
            ;;

    *)      # Calculate the requested VSI setting. Mpage does not support
            # directly setting VSI.  Instead, it accepts a setting for the
            # maximum number of lines you want to fit on the page.  So, we
            # look at how the report will print on the page (port or land)
            # and based on that, we figure out how many rows will fit. For
            # this calculation, we assume a page size of 7.5 by 10 inches. 
            # This is what you would get with a 60 line report printed at 6 
            # lpiin portrait mode and a 60 line report printed at 8 lpi in 
            # landscape mode.  Since the shell can't handle non integer
            # math, for the 7.5, we calc with 75 and then devide the result
            # by 10 to maintain precision.

            case "$orientation" in
                def|port*) arglist="$arglist -L$(( 10 * 48 / $vsi      ))"
                           ;;
                land*)     arglist="$arglist -L$(( 75 * 48 / $vsi / 10 ))"
                           ;;
            esac
            ;;
esac

#
# Did we get a request for a custom Lines Per Page setting?
#

case "$pagelen" in
    def)    # Do nothing if the field was not set on the command line
            ;;

    *)      # This is easy, The Mpage setting for lines per page is -L{#lines}

            arglist="$arglist -L$pagelen"
            ;;
esac

#
# Did we get a request for a custom Font setting?
#

case "$font" in
    def)    # Do nothing if the field was not set on the command line
            ;;

    *)      # Request the specified font

            arglist="$arglist -F$font"
            ;;
esac

#
# Did we get a request to collate?
#

case "$collate" in
    def)    # Do nothing if the field was not set on the command line
            ;;

    *)      # Request the specified setting.  (not supported by MPAGE)
            ;;
esac

#
# Now add any arguments we didn't parse out.  They should already be raw Mpage arguments.
#

arglist="$arglist $args"

#
# Log what we did
#

echo "mpage cmd: mpage $arglist" >>$log
echo "" >> $log

# Now pass the print file data on through mpage

mpage $arglist

# all done

echo "==========[ Exiting filter ]================================================" >> $log

exit 0

#+###########################################################################
#+ Modification History
#+
#+ DATE      BY   Description
#+ --------  ---  ---------------------------------------------------------
#+ 03/21/01  PHB  Initial Creation
#+ 11/08/04  PHB  Added -point= option
#+###########################################################################
