#!/bin/bash
#
# faxdvi2 -- pass a DVI file to the FAX subsystem.
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#
# Ralph Schleicher
# rs@purple.in-ulm.de


# Configure these to suite your needs.
#
dvips="dvips -t letter -P fax"
gs="gs -sPAPERSIZE=letter -sDEVICE=dfaxhigh"

# Try to be a little bit user friendy.
#
help=0
for arg
do
  case $arg in
    -?|--help) help=1;;
  esac
done

if [ $# -lt 2 -o $help -eq 1 ]
then
  echo "Usage:  faxdvi2 [<options>] <phone-number> <dvi-file>[.dvi]"
  echo ""
  echo "	<options>"
  echo "		Will be passed verbatim to DVIPS."
  echo "	<phone-number>"
  echo "		A real phone number or a FAX alias."
  echo "	<dvi-file>"
  echo "		You name it."

  if [ $help -eq 1 ]
  then
    exit 0
  else
    exit 1
  fi
fi

# I should write it in Perl.
#
die ()
{
  echo -en $*

  exit 1
}

# Argument handling.
#
opt=""
while [ $# -gt 2 ]
do
  opt="$opt $1"
  shift
done

num=$1
dvi=$2

if [ ! -f $dvi ]
then
  if [ -f $dvi.dvi ]
  then
    dvi="$dvi.dvi"
  else
    die "$0:$dvi: No such file\n"
  fi
fi

# Cleanup on exit or if an error occurs.
#
temp="/tmp/faxdvi.$$"

rm -fr $temp >/dev/null 2>&1
mkdir $temp >/dev/null 2>&1 || die "$0:$temp: Permission denied\n"

trap "rm -fr $temp >/dev/null 2>&1" \
  EXIT SIGHUP SIGINT SIGQUIT SIGKILL SIGPIPE SIGTERM

# It's time to do the real work.
#
name="$temp/f"

$dvips $opt -o $name $dvi >/dev/null 2>&1 ||
  die "$0: DVIPS failed for some reason\n"

$gs -dNOPAUSE -sOUTPUTFILE=${name}%07d.g3 $name quit.ps >/dev/null 2>&1 ||
  die "$0: Ghostscript failed for some reason\n"

faxspool "$num" `ls $name*.g3` >/dev/null 2>&1 ||
  die "$0: Sending \`$dvi' to \`$num' failed\n"

# I can't believe it!
#
exit 0
