#!/bin/sh
#
# Start a postscript viewer to display the current plot for pyxplot
#
# The system /etc/pyxplotrc, the user's ~/.pyxplotrc and the .pyxplotrc in 
# the current directory are searched in turn to find a configured postscript
# viewer. If none is found, then a list of common postscript viewers is
# searched.
#
# Configuration in the pyxplotrc files is done as:
#
#   GV=/usr/local/bin/best_gv
#   GV_OPTIONS=--watch 5
#
# to specify some other viewer and some command line arguments. The GV
# parameter must be given an absolute path to the viewer.
#
##############################################################################
#
# gv_wrapper is part of the Debian pyxplot package
#
#      Copyright (c) 2009 Stuart Prescott
#
#      gv_wrapper is distributable under the same terms as pyxplot itself
#      (GNU GPL version 2 or later)
#
##############################################################################


importConfig () {
  local confgv confgvo
  if [ ! -r $1 ]
  then
    return
  fi
  confgv=$(sed -n 's/GV[ \t]*=[ \t]*\(.*\)/\1/p' $1)
  if [ -n $confgv ]
  then
    GV="$confgv"
  fi
  confgvo=$(sed -n 's/GVOPTIONS[ \t]*=[ \t]*\(.*\)/\1/p' $1)
  if [ -n $confgvo ]
  then
    GV_OPTIONS="$confgvo"
  fi
}


autoViewer() {
  for viewer in /usr/bin/gv /usr/bin/kghostview /usr/bin/okular /usr/bin/evince
  do
    if [ -x $viewer ]
    then
      GV=$viewer
      return
    fi
  done
  echo "Error: no postscript viewer found. See /usr/share/doc/pyxplot/README.Debian" 1>&2
  exit 1
}

# start by searching the config files
for config in /etc/pyxplotrc ~/.pyxplotrc .pyxplotrc
do
  importConfig $config
done

# if nothing is configured explicitly, then try to find a suitable viewer
if [ -z $GV ]
then
  autoViewer
fi


# try it out
if [ -x $GV ]
then
  #echo "Found ghostscript viewer $GV"
  if [ $GV = "/usr/bin/gv" ]
  then
    # pass the --watch option to gv
    exec "$GV" $GV_OPTIONS "$@"
  else
    # don't pass the --watch option that will confuse other viewers
    exec "$GV" $GV_OPTIONS "$2"
  fi
else
  echo "Error: Configured postscript viewer not found. See /usr/share/doc/pyxplot/README.Debian" 2>&1
  exit 1
fi

