#!/bin/csh -f

# Usage:

#   progname
#     [-recipients recipients]
#     [-faxopts fax-options]
#     [-mailopts mail-options]
#     [general-options]

# where progname is one of:
#   sendfax-or-sendmail
#   sendfax-or-Mail

# The possibilities could easily be expanded to allow other fax and
# mail sending programs.

# The standard input contains the body of the message to be sent,
# possibly preceded by a header.

# The argument blocks can be in any order; only the last one of any
# given type is effective.  If none of the switches above is present,
# the default is to start out looking for mail-options (for the
# benefit of sending from emacs).  Default fax-options and
# mail-options are chosen by a switch near the beginning of the script
# according to the fax or mail program in the name with which the
# script is invoked.  At present the only possible general options are
# +mailselfblind (default) and -mailselfblind.  The +mailselfblind
# option is more powerful than the typical use of a -b flag in a mail
# command.  Rather than mailing to $EADDR a replica of what everybody else
# gets, in which Bcc recipients do not show, the +mailselfblind option
# generates a separate message to $EADDR that shows the Bcc recipients
# with an X-Bcc header field.

# Note that if this script can recognize a mail option saying to take
# recipients from a header in the input, it strips out that option,
# and takes recipients (including fax recipients) from the header on
# its own (and removes any Bcc field).  In particular "-t" for
# sendmail or Mail causes this script to consult the header.  (Other
# mail commands could also be associated with *always* or *never*
# looking for a header.)  Whenever recipients are sought in a header
# in the input, an attempt is also made to obtain From and Subject
# information.  These items are used for -r and -s options for Mail
# and for -f (may not be effective for average user) and -r options
# for sendfax.  Also, when this script processes an input header, it
# strips it away before sending input the fax program.  It is,
# however, retained for the mail program.  (Sendmail will handle the
# header items intelligently, while Mail will just take it as part of
# the message body since the -t option is stripped.)  In addition, the
# full header is provided to the -c option for sendfax.  Command line
# arguments override any information in the header.  The section on
# "SOFTWARE CUSTOMIZATION" below is used to indicate how particular
# mail and fax commands should be treated.  Note that header here is
# defined as everything through the first blank line, and the header
# is assumed to be unfolded.

# Addresses ending in ".FAX" are treated as fax addresses; the others
# as email addresses.  Note that parentheses really should be removed
# from phone numbers before they are used in fax addresses, because
# mail readers may interpret them strangely.  This script removes
# everything except "+" and digits from phone numbers and then
# massages the phone number according to the "DIALING CUSTOMIZATION"
# section.

# There should be no spaces (even quoted) in any of the arguments.

set debug = 0
# Always log actions
#> 0: Log input, output header, output body
#> 1: Print actions and don't do them
#> 2: Print intermediate information
#> 3: Print even info on fax address manipulations

umask 66

set noglob

set fullprogname = $0
set fullprogname = `echo $fullprogname | sed 's+^\([^/]\)+./\1+'`
set progdir = $fullprogname:h
set progname = $fullprogname:t
set faxprog = "`expr $progname : '\(.*\)-or-.*'`"
set mailprog = "`expr $progname : '.*-or-\(.*\)'`"

if ($debug > 2) then
  echo progname: $progname
  echo faxprog: $faxprog
  echo mailprog: $mailprog
endif

set tempinp = /tmp/$progname.inp.$user.$$
set temphead = /tmp/$progname.head.$user.$$
set tempheadcull = /tmp/$progname.headcull.$user.$$
set tempmodhead = /tmp/$progname.modhead.$user.$$
set tempbody = /tmp/$progname.body.$user.$$
set tempscript = /tmp/$progname.script.$user.$$
set temperrors = /tmp/$progname.errors.$user.$$

set inplog = $progdir/inp.log
set headlog = $progdir/head.log
set modheadlog = $progdir/modhead.log
set bodylog = $progdir/body.log
set actlog = $progdir/act.log

# BEGIN DIALING CUSTOMIZATION

set origincc = 1
set originac = 773

set outdial = 9
set lddial = 1
set intdial = 011

# END DIALING CUSTOMIZATION

# BEGIN SOFTWARE CUSTOMIZATION


set faxfromflag = ""
set faxsubjflag = ""
set faxcommflag = ""
set faxopts = ""
switch ($faxprog)
  case sendfax:
    set faxopts = "-D -R -m"
#    set faxfromflag = "-f" # only effective for root, daemon, or uucp user
    set faxsubjflag = "-r"
    set faxcommflag = "-c"
    breaksw
endsw

set mailfromflag = ""
set mailsubjflag = ""
set mailopts = ""
set recipsinheadopt = '$^' # sed pattern that never matches
set ccincmdlineopt = '$.^' # egrep pattern that never matches
set interactiveopt = '$.^' # egrep pattern that never matches
set mailerrors = '$^' # sed pattern that never matches
switch ($mailprog)
  case sendmail:
    set recipsinheadopt = "-t" # sed pattern
    set interactiveopt = "(-od|-odi)" # egrep pattern
    set mailerrors = "-oem" # sed pattern
#    set mailfromflag = "-f"
    breaksw
  case Mail:
    set expandals
    set recipsinheadopt = "-t" # sed pattern
    set ccincmdlineopt = "(-b|-c)" # egrep pattern
    set mailfromflag = "-r"
    set mailsubjflag = "-s"
    breaksw
  default:
    set expandals # probably desirable for most other mail programs
endsw

# END SOFTWARE CUSTOMIZATION

set mailselfblind # a general option

set recipients = ""

set mode = "-mailopts"

while ($#argv > 0)
  set arg = "$1"
  shift
  switch ("$mode$arg")
  case *+mailselfblind:
    set mailselfblind
    breaksw
  case *-mailselfblind:
    unset mailselfblind
    breaksw
  case *-faxopts:
    set faxopts = ""
    set mode = "-faxopts"
    breaksw
  case *-mailopts:
    set mailopts = ""
    set mode = "-mailopts"
    breaksw
  case *-recipients:
    set recipients = ""
    set mode = "-recipients"
    breaksw
  case -faxopts*:
    set faxopts = "$faxopts $arg"
    breaksw
  case -mailopts*:
    set mailopts = "$mailopts $arg"
    breaksw
  case -recipients*:
    set recipients = ($recipients $arg)
  endsw
end

if ($debug > 2) then
  echo faxopts: "$faxopts"
  echo mailopts: "$mailopts"
  echo cmd-line-recipients: $recipients
  echo genopts: 'mailselfblind?': "$?mailselfblind"
endif

cat > $tempinp

set from = ""
set subj = ""
set comm = ""

echo "$mailopts" | grep "\$recipsinheadopt" > /dev/null
if (! $status) then
  set mailopts = (`echo "$mailopts " | sed -n "s+$recipsinheadopt ++p"`)
  sed -n '1,/^$/p' $tempinp \
    | sed 's+^[Bb][Cc][Cc]:+X-Bcc:+\
           s+^++\
           s+^[ 	][ 	]*+ +' \
    | tr -d '\012' | tr '' '\012' | tail -n +2 > $temphead
    echo '' >> $temphead
    # above four lines unfold the header
  sed -n 's+,+ +g\
          s+^[Tt][Oo]:++p\
          s+^[Cc][Cc]:++p\
          s+^[Xx]-[Bb][Cc][Cc]:++p' $temphead > $tempheadcull
  # Changed from "egrep -i ..." to allow long lines
  set recipients = (`cat $tempheadcull`)
  set from = "`sed -n 's+^[Ff][Rr][Oo][Mm]:[ 	]*++p' $temphead`"
  set subj = "`sed -n 's+^[Ss][Uu][Bb][Jj][Ee][Cc][Tt]:[ 	]*++p' $temphead | tr -d '\047'`"
  # Removes apostrophes from subj to avoid messup when invoking shell command
  sed '/^X-Bcc:/d\
       /^X-emacs-local-variables:/d' $temphead > $tempmodhead
  # Changed from "egrep -v ..." to allow long lines
  sed 's+^[Ss][Uu][Bb][Jj][Ee][Cc][Tt]:.*++\
       s+^[Dd][Aa][Tt][Ee]:.*++\
       s+^[Ff][Rr][Oo][Mm]:.*++' $tempmodhead > $tempheadcull
  # Changed from "egrep -iv ..." to allow long lines
  set comm = (`cat $tempheadcull | tr '_' ' '`)
  sed -n '/^$/,$p' $tempinp | tail -n +2 > $tempbody
else
  cp $tempinp $tempbody
  rm -f $temphead $tempmodhead
  touch $temphead $tempmodhead
endif

if ($debug > 2) cat $temphead

if ($debug) then
  cat $tempinp > $inplog
  cat $temphead > $headlog
  cat $tempmodhead > $modheadlog
  cat $tempbody > $bodylog
endif

if ("$from" == "") then
  set faxfromflag = ""
  set mailfromflag = ""
endif
if ("$subj" == "") then
  set faxsubjflag = ""
  set mailsubjflag = ""
endif

if ($debug > 2) then
  echo mailopts: "$mailopts"
  echo recipients: $recipients
  echo from: "$from"
  echo "faxfromflag: $faxfromflag, mailfromflag: $mailfromflag"
  echo subj: "$subj"
  echo "faxsubjflag: $faxsubjflag, mailsubjflag: $mailsubjflag"
  echo "faxcommflag: $faxcommflag"
  echo comm: $comm
endif

set eaddrs = ""
set faddrs = ""
while ($#recipients > 0)
  set arg = "$recipients[1]"
  if ("$arg" == "") continue
  shift recipients
  switch ("$arg")
  case *@*.FAX:
    set faddrs = ($faddrs $arg)
    breaksw
  case *@*:
    set eaddrs = ($eaddrs $arg)
    breaksw
  default:
    set expansion = ""
    if ($?expandals) set expansion = "`sed -n 's/^[ 	]*alias[ 	][ 	]*'$arg'[ 	][ 	]*/ /p' $HOME/.mailrc | tr ',' ' '`"
    if ("$expansion" == "") then
      set eaddrs = ($eaddrs $arg)
    else
      set recipients = ($expansion $recipients)
    endif
  endsw
end

if ($debug > 2) then
  echo eaddrs: $eaddrs
  echo faddrs: $faddrs
endif

set faddrfixes = ""
foreach faddr ($faddrs)
  set person = (`echo "$faddr" | cut -d@ -f1`)
  if ($debug > 3) echo "person: $person"
  set faxno = (`expr "$faddr" : '.*@\(.*\).FAX' | tr -d '_.-'`)
  if ($debug > 3) echo "faxno: $faxno"
  set faxnofix = `echo $faxno | sed -n s/^+$origincc$originac/$outdial/p`
  if ("$faxnofix" == "") set faxnofix = \
     `echo $faxno | sed -n s/^+$origincc/$outdial$lddial/p`
  if ("$faxnofix" == "") set faxnofix = \
     `echo $faxno | sed -n s/^+/$outdial$intdial/p`
  if ("$faxnofix" == "") set faxnofix = \
     `echo $faxno | sed -n s/^$originac'\(.......\)$'/$outdial'\1'/p`
  if ("$faxnofix" == "") set faxnofix = \
     `echo $faxno | sed -n s/'^\(..........\)$'/$outdial$lddial'\1'/p`
  if ("$faxnofix" == "") set faxnofix = \
     `echo $faxno | sed -n s/'^\(.......\)$'/$outdial'\1'/p`
  if ("$faxnofix" == "") set faxnofix = "$faxno"
  set faddrfixes = "$faddrfixes $person@$faxnofix"
end

set faddrfixes = (`echo "$faddrfixes " | tr ' ' '\012' | sort -u`)

if ($debug > 2) then
  echo faddrfixes: $faddrfixes
endif

# If there are cc recipients in the command line but no ordinary
# recipients, use $EADDR as an ordinary recipient so that the mail will
# be sent.
echo "$mailopts" | egrep "$ccincmdlineopt" > /dev/null
if (! $status) then
  if ("$eaddrs[1]" == "") set eaddrs = ($EADDR)
endif

if ($debug > 2) echo eaddrs: $eaddrs

rm -f $tempscript
touch $tempscript

if ($?mailselfblind) then
  echo -n "cat $temphead $tempbody | $mailprog" >>$tempscript
  if ("$mailfromflag" != "") echo -n " $mailfromflag" \'"$from"\' >>$tempscript
  if ("$mailsubjflag" != "") echo -n " $mailsubjflag" \'"$subj"\' >>$tempscript
  echo " $mailopts $EADDR" >> $tempscript
endif
if ("$eaddrs[1]" != "") then
  echo -n "cat $tempmodhead $tempbody | $mailprog" >> $tempscript
  if ("$mailfromflag" != "") echo -n " $mailfromflag" \'"$from"\' >>$tempscript
  if ("$mailsubjflag" != "") echo -n " $mailsubjflag" \'"$subj"\' >>$tempscript
  echo " $mailopts " $eaddrs >> $tempscript
endif

foreach faddrfix ($faddrfixes)
  echo -n "cat $tempbody | $faxprog" >> $tempscript
  if ("$faxfromflag" != "") echo -n " $faxfromflag" \'"$from"\' >> $tempscript
  if ("$faxsubjflag" != "") echo -n " $faxsubjflag" \'"$subj"\' >> $tempscript
  echo " $faxcommflag" \'"$comm"\' "$faxopts -d" \'"$faddrfix"\' >> $tempscript
end

if ($debug > 1) then
  cp $tempscript $actlog
  cat $actlog
else
  (cat $tempscript | /bin/csh -fv > $actlog)  >& $temperrors
  # $actlog gets standard outputs from commands
  # $temperrors gets echoed commands and error outputs
  cat $temperrors >> $actlog
  set scriptlength = `cat $tempscript | wc -l`
  set errorslength = `cat $temperrors | wc -l`
  if ($errorslength > $scriptlength) then
    echo "$mailopts" | egrep "$mailerrors" > /dev/null
    if ($status) then
      cat $actlog
    else
      mail $EADDR < $actlog
    endif
  endif
endif

rm -f $tempinp $temphead $tempheadcull $tempmodhead $tempbody $tempscript $temperrors
