#!/bin/sh
# ====================[ dotfm-evince                       ]====================
#                     [ Time-stamp: "2009-04-24 18:42:15 leycec" ]             
#
# --------------------( TODO                               )--------------------
# * Incorporate the "--twoside" logic into "fragmaster.pl" itself and contribute
#   back, preferably as a generalized option accepting a page or page range.
# * In fact, most of this script can (and should) be incorporated into
#   "fragmaster.pl" itself. For example, if that script finds a
#   "${BASENAME}_fm" file and "${BASENAME}_fm.dot" file but no corresponding
#   "${BASENAME}_fm.eps" file, then it should automatically generate that EPS
#   file from that DOT file just as we do below.
#
# --------------------( CHANGELOG                          )--------------------
# 2009-08-12  Cecil Curry  <http://raiazome.com>
#   * Created.

# ....................{ CONSTANTS                          }....................
SCRIPT_NAME=$(basename "$0")
SCRIPT_VERSION="0.0.1"

# ....................{ I/O HANDLING                       }....................
mutter() {
  echo -n "${SCRIPT_NAME}: $*"
}

utter() {
  if [ -n "$IS_CRON" ]
  then logger -p cron.notice "${SCRIPT_NAME}: $*"
  else echo "${SCRIPT_NAME}: $*"
  fi
}

curse() {
  if [ -n "$IS_CRON" ]
  then logger -p cron.err "${SCRIPT_NAME}! $*"
  else echo "${SCRIPT_NAME}! $*" 1>&2
  fi
}

utter_usage_error() {
  utter_usage
  exit 1
}

utter_usage_noerror() {
  utter_usage
  exit 0
}

utter_usage() {
  echo "Usage: ${SCRIPT_NAME} [options] file...
             options
  -h, --help              Show this help.
  -2, --twoside           Treat dot EPS file output as consisting of two pages.
  -s, --strip-first-page  Strip the first page from all output PDF files."
}

# ....................{ ERROR HANDLING                     }....................
try() {
  $*

  # Ensure we clean up after a failed "fragmaster.pl" run.
  if [ $? -ne 0 ]; then
    tidy
    exit 1
  fi
}

die() {
  curse $*
  exit 1
}

# ....................{ OPTION PARSING                     }....................
OPTIONS=$(getopt --unquoted --longoption 'twopage,help' --options '+2,h' --shell sh -- "${@}")
[ $? = 0 ] || utter_usage_error

set -- $OPTIONS

# Disable the $TWOSIDE option, by default.
TWOSIDE=""

# Parse all command-line options.
while [ $# -gt 0 ]; do
  case "$1" in
    --help) utter_usage_noerror;;
    -h)     utter_usage_noerror;;
    --twoside) TWOSIDE=1; shift;;
    -2)        TWOSIDE=1; shift;;
    --) shift; break;;
    -*) utter_usage_error;;
    *)  break;;
  esac
done

# Store all remaining command-line parameters.
BASENAME=$(echo "$1" | sed "s/\.dot$//")

# ....................{ IMPLEMENTATION                     }....................
main() {
  # Ensure the appropriate input files actually exist.
  [ -f "${BASENAME}.dot" ] || die "'${BASENAME}.dot' not found!"
  [ -f "${BASENAME}_fm"  ] || die "'${BASENAME}_fm' not found!"

  # Print a preface.
  if [ -n "$TWOSIDE" ]
  then utter "{welcome!} assuming two-sided input..."
  else utter "{welcome!} assuming one-sided input..."
  fi

  # Convert the input Graphviz document to an intermediary Postscript document.
  # Note our use of the "-Tps2" option rather than the customary "-Tps" option;
  # the former is a variant of the latter informing Graphviz that that Postscript
  # document is intended to be converted into a PDF document at some later stage,
  # and that Graphviz should therefore adjust and optimize that Postscript
  # document accordingly. (A small point, but quite helpful.)
  utter "[dot] converting '${BASENAME}.dot' to '${BASENAME}_fm.eps'..."
  try dot -Tps2 "${BASENAME}.dot" 1>"${BASENAME}_fm.eps"

  if [ -n "$TWOSIDE" ]; then
    utter "[psselect] converting '${BASENAME}_fm.eps' to '${BASENAME}-(1|2)_fm.eps'..."
    try psselect 1 "${BASENAME}_fm.eps" "${BASENAME}-1_fm.eps"
    try psselect 2 "${BASENAME}_fm.eps" "${BASENAME}-2_fm.eps"

    utter "[sh] removing '${BASENAME}_fm.eps' and linking '${BASENAME}_fm'..."
    try rm     "${BASENAME}_fm.eps"
    try ln -sf "${BASENAME}_fm" "${BASENAME}-1_fm" 
    try ln -sf "${BASENAME}_fm" "${BASENAME}-2_fm" 

    #FIXME: "--select_second_page" should be a configurable option.
    utter "[fm] converting '${BASENAME}-(1|2)_fm.eps' to '${BASENAME}-(1|2).pdf'..."
    try fragmaster.pl #--select_second_page

    utter "[sh] unlinking '${BASENAME}_fm'..."
    try rm "${BASENAME}-1_fm" "${BASENAME}-2_fm"
#   try rm "${BASENAME}-2_fm"

    utter "[evince] viewing '${BASENAME}-(1|2).pdf'..."
    evince "${BASENAME}-1.pdf" "${BASENAME}-2.pdf" &
  else
    utter "[fm] converting '${BASENAME}_fm.eps' to '${BASENAME}.pdf'..."
    try fragmaster.pl --select_second_page

    utter "[evince] viewing '${BASENAME}.pdf'..."
    evince "${BASENAME}.pdf" &
  fi
}

tidy() {
  #FIXME: Should probably add a "--no-tidy" option for enabling an early return.
# return
  utter "[sh] removing intermediary files..."
  mv --force "fm-${BASENAME}"* "${BASENAME}"*.eps /tmp 1>/dev/null 2>&1
  [ -n "$TWOSIDE" ] && rm "${BASENAME}-1_fm" "${BASENAME}-2_fm" 1>/dev/null 2>&1
}

# ....................{ MAIN                               }....................
# Iku ze!
main
tidy

# --------------------( COPYRIGHT AND LICENSE              )--------------------
# The information below applies to everything in this distribution,
# except where noted.
#              
# Copyleft 2009 by B.w.Curry.
#   
#   http://www.raiazome.com
# 
# 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 3 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, see <http://www.gnu.org/licenses/>.
