#!/usr/bin/env bash

# Copyright (C) 2008-2015 Bob Hepple
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# http://bhepple.freeshell.org

error_exit() {
    echo "Use '$PROG -h' for usage" >&2
    exit 1
}

check_and_process_opts() {
    local TEMP

    ARGS="
ARGP_DELETE=quiet
ARGP_VERSION=$VERSION
ARGP_PROG=$PROG
##############################################################   
#OPTIONS:
#name=default sname arg       type range   description
##############################################################   

##############################################################   
ARGP_ARGS=[--] $ARGUMENTS
ARGP_SHORT=$SHORT_DESC
ARGP_USAGE=$USAGE"

    exec 4>&1
    eval $(echo "$ARGS" | argp.sh "$@" 3>&1 1>&4 || echo exit $? )
    exec 4>&-

    NEW_ARGS=( "$@" )
    return 0
}

##########################
#         M A I N        #
##########################

PROG=$(basename $0)
VERSION="1.2"
PS2PDF=ps2pdf
SECT_OPT=""
case `uname` in
    SunOS)
        SECT_OPT="-s "
        break
        ;;
esac
SHORT_DESC="wrapper around man"
USAGE="\
A wrapper for 'man'. Depends on the script 'v' available from the same place.

Displays a pretty man page if X is available (otherwise just does 'man'). \
'section' narrows the search for a man page to that section. \
'name' is the name of the manual page.

On Solaris, adds the '-s' option for section name. \
eg. Do 'm man' for more information about 'man'"
ARGUMENTS="[ section ] name"
VERBOSE=""

NEW_ARGS=( )
check_and_process_opts "$@" && set -- "${NEW_ARGS[@]}"

if [ $# -eq 0 ]; then
    echo "$PROG: at least 'name' is required" >&2
    error_exit
fi

if [ $# -gt 2 ]; then
    echo "$PROG: too many arguments" >&2
    error_exit
fi

SECT=""
if [ $# -gt 1 ]; then
    SECT="$SECT_OPT$1"
    shift
fi
INFILE="$1"

[ -z "$DISPLAY" ] && exec man $SECT "$INFILE"

TMPFILE=/tmp/m.tmp.$$
UNZIPFILE=/tmp/in.tmp.$$
trap "rm -f $UNZIPFILE $TMPFILE.ps $TMPFILE.pdf" EXIT

[ "$VERBOSE" ] && set -x

case "$INFILE" in
    *.gz)
        gunzip -c "$INFILE" >"$UNZIPFILE"
        INFILE="$UNZIPFILE"
        ;;
    *)
        :
        ;;
esac

if man -t $SECT "$INFILE" >$TMPFILE.ps; then
    if type $PS2PDF &>/dev/null; then
        $PS2PDF $TMPFILE.ps $TMPFILE.pdf
        v -X $TMPFILE.pdf
    else
        v -X $TMPFILE.ps
    fi
else
    exec man $SECT "$INFILE"
fi

