#!/bin/csh -f

# Copyright (c) 1991, Andrew Rosen.
# All rights reserved.
#
# This  software is supplied free of charge.  This software, or any part
# of it,  may  not  be  redistributed or otherwise made available to, or
# used  by,  any  other  person  without the inclusion of this copyright
# notice.  This software may not be used to make a profit in any way.
#
# This  software  is provided with absolutely no warranty, to the extent
# permitted  by  applicable  state law.  In no event, unless required by
# applicable law,  will the author(s) of this software be liable for any
# damages caused by this software.


source ~acs/acs-vars
cd ${acsdir}

set file = $argv[1]

source get-address
if ( ${quit} == "yes" ) then
  goto done
endif

# Check if user has an alias
source check-alias

if ( ${status} == 0 ) then
  # User does not have an alias
  source give-alias
endif


## Save subject of message
source get-subject


## Save alias mail is being sent to
set to = "`echo ${file:t} | cut -d'.' -f1-2`"
echo "Message is being sent to alias ${to}"

# See if recipient alias really exists
ggrep -s "^${to}:" ${aliasdb}
if ( ${status} != 0 ) then
  # No alias exists, bounce to sender
  cat >! /tmp/anon-mess.$$ << EOF
Subject: ACS reply (Re: ${subject})
To: ${address}
Reply-To: ${adminuser}@${server}
X-ACS2-Version: ${version}

Your mail could not be received by ${to}@${server}

There is no such alias as ${to}.

Your message could not be fowarded and
has been removed from the ACS system.
EOF
  cat ${signature} >> /tmp/anon-mess.$$
  cat /tmp/anon-mess.$$ | sendmail ${address}

  echo "Bounced mail to ${address}, no alias ${to}"

  rm -f /tmp/anon-mess.$$ ${file}

  exit 1
endif

## Alias exists, get real address
set real = `ggrep "^${to}:" ${aliasdb} | cut -d':' -f2 | cut -d' ' -f1`


## Extract body of message, excluding any signature
# First see if there's a signature
cp ${file} /tmp/ap.reply
ggrep -s '^--' /tmp/ap.reply
if ( ${status} == 0 ) then
  # There is, strip it
  ed /tmp/ap.reply << EOF
/^\-\-/
.,\$d
w
q
EOF
endif

# Append two blank lines (fixes potential security hole)
echo "" >> /tmp/ap.reply
echo "" >> /tmp/ap.reply

# Now fix header, leaving old Subject: line
ed /tmp/ap.reply << EOF
1,/^\$/d
i
From: ${alias}@${server} ${name}
Subject: ${subject}
Reply-To: ${alias}@${server}
X-To-ACS-Alias: ${to}


.
w
q
EOF


## Mail stripped message to recipient
cat /tmp/ap.reply | sendmail -f "${alias}@${server} ${name}" ${real}
echo "Sent reply mail to ${to} (${real})"

# Clean up
done:
rm -f ${file} /tmp/ap.reply
exit 0
