#! /bin/sh

# That's the modified original SmartList subscribe script to overcome security
# implications and limititations caused by multigram. It's only used if 
# require_confirm is set to yes

test=test		# /bin/test
echo=echo		# /bin/echo
cat=cat			# /bin/cat
sed=sed			# /bin/sed
grep=grep		# /bin/grep
date=date		# /bin/date
formail=formail		# /usr/local/bin/formail
multigram=multigram	# ../.bin/multigram
arch_retrieve=arch_retrieve	# ../.bin/arch_retrieve

tmprequest=tmp.request
tmpfrom=tmp.from
subscribetxt=subscribe.txt
subscribefiles=subscribe.files

$test -z "$listaddr" &&
 $echo "Don't start this script directly, it is used in rc.request" && exit 64

subscraddr="$1"
$test -z "$subscraddr" &&
 $echo "Error: missing address to subscribe" && exit 64

if $test ! -r dist
then
  $echo "subscribe: Where did the dist file go?" 1>&2
  $echo "(Only addresses below this line can be automatically removed)" >>dist
fi

case "$X_ENVELOPE_TO" in
  *$list-request*) wrongaddress="" ;;
  *) wrongaddress="WARNING:
	Please try to use '$listreq'
	the next time when issuing (un)subscribe requests.
" ;;
esac

if $test -f subscreen
then
  ./subscreen "$subscraddr" || exit 1
fi

$grep '^Subject: Re:' <$tmprequest >/dev/null &&
  wrongaddress="${wrongaddress}WARNING:
	Send in a new mail, INSTEAD OF REPLYING
	the next time when issuing (un)subscribe requests.
"

$multigram -a "$subscraddr" dist >/dev/null

sender=`$formail -rtzcxTo: <$tmprequest`

$test -z "$subscribe_log" ||
 $echo "subscribe: $subscraddr by: $sender  `$date`" >>$subscribe_log

case $subscraddr in
   *$sender*) sender="$subscraddr" ;;
   *) sender="$sender $subscraddr" ;;
esac

( $formail -i"From: $listreq" -rtA"X-Loop: $listaddr" <$tmprequest

  $test ! -z "$wrongaddress" && $echo "$wrongaddress" && wrongaddress=""

  $echo "You have added to the subscriber list of:"
  $echo ""
  $echo "	$listaddr"
  $echo ""
  $echo "the following mail address:"
  $echo ""
  $echo "	$subscraddr"
  $echo ""
  $echo "By default, copies of your own submissions will be returned."
  $echo ""

  $cat $subscribetxt

  $sed -e 's/^/>/' $tmprequest
) | $SENDMAIL $sendmailOPT $sender

if $test -f $subscribefiles
then
  $formail -X "" -i "Reply-To: $subscraddr" -i "Subject: archive" \
   <$tmprequest >$tmpfrom
  $cat $tmpfrom >$tmprequest
  $echo "" >>$tmprequest
  $cat $subscribefiles >>$tmprequest		# setup fake archive commands
  $echo $subscraddr >$tmpfrom
  exec $arch_retrieve <$tmprequest		# the point of no return
fi
