#! /bin/bash

## 
## Usage: @PROG@ [SECTION] PAGE
## 
##   Display the specified manual page using gxmessage
## 


PROG=$(basename $0)
XMESSAGE=${XMESSAGE:-$(which gxmessage)} || XMESSAGE=xmessage

MSG_TITLE=$PROG
MSG_FONT="monospace"
MSG_FG=
MSG_BG=
MSG_GEOM=
MSG_POS=-center


[ "$XMESSAGE" = xmessage ] && MSG_FONT=


invocationError ()
{
  echo "Try '$PROG -h'" >&2
  exit 64
}


showUsage ()
{
  sed -n '/^##/s/^## //p' $0 | sed -e "s/@PROG@/${PROG}/g"
  exit 0
}


getPrompt ()
{
cat <<-ENDPROMPT
	What manual page do you want?
	E.g.: [SECTION] PAGE
ENDPROMPT
}


[ "$1" = "-h" -o "$1" = "--help" ] && showUsage

if [ "$#" -eq 2 ]; then
  sect=$1
  shift
fi

if [ "$#" -eq 1 ]; then
  page=$1
elif [ "$#" -eq 0 -a "$XMESSAGE" != xmessage ]; then
  # the -entry option here is not xmessage-compatible
  page=$(getPrompt | $XMESSAGE ${MSG_FONT:+-fn "$MSG_FONT"} \
                               ${MSG_FG:+-fg "$MSG_FG"}     \
                               ${MSG_BG:+-bg "$MSG_BG"}     \
                               -bu ""                       \
                               -title "$MSG_TITLE"          \
                               $MSG_POS                     \
                               -entry                       \
                               -file - )
  [ -z "$page" ] && exit 0
  sect=${page%% *}
  page=${page##* }
  [ "$sect" = "$page" ] && sect=
else
  invocationError
fi

man $sect $page 2>&1 | col -b |
    $XMESSAGE ${MSG_GEOM:+-geom "$MSG_GEOM"}  \
              ${MSG_FONT:+-fn "$MSG_FONT"}    \
              ${MSG_FG:+-fg "$MSG_FG"}        \
              ${MSG_BG:+-bg "$MSG_BG"}        \
              -bu "GTK_STOCK_CLOSE:0"         \
              -title "$MSG_TITLE"             \
              $MSG_POS                        \
              -default GTK_STOCK_CLOSE        \
              -file -

