#!/bin/sh
#
# Copyright (C) 2001-2018 Graeme Walker <graeme_walker@users.sourceforge.net>
#
# 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/>.
# ===
#
# emailrelay-submit.sh
#
# An example script that deposits e-mail messages into sub-directories
# of the main E-MailRelay spool directory depending on the "To:"
# address. This could be used with an E-MailRelay POP server running
# with the "pop-by-name" option so that messages get routed appropriately.
#
# usage: emailrelay-submit.sh
#

store="/var/spool/emailrelay"
log="/var/log/emailrelay-submit.out"
awk="awk" # nawk

tmp="/tmp/`basename $0.$$.tmp`"
trap "rm -f \"${tmp}\" 2>/dev/null ; exit 0" 0
trap "rm -f \"${tmp}\" 2>/dev/null ; exit 1" 1 2 3 13 15

List()
{
	# Maps from the given "To:" address to a spool subdirectory -- edit as required
	to_="${1}"
	to_="`echo \"${to_}\" | tr '[A-Z]' '[a-z]'`"
	case "${to_}" in
		me@*) echo me_1 me_2 ;;
		other@*) echo other_1 other_2 ;;
		*) echo postmaster ;;
	esac
}

Create()
{
	# Creates a spool subdirectory if it doesnt already exist
	dir_="${1}"
	if test ! -f "${dir_}"
	then
		echo `basename $0`: creating directory \"${dir_}\"
		mkdir "${dir_}"
		chown root:daemon "${dir_}"
		chmod 775 "${dir_}"
	fi
}

Main()
{
	# take a copy of the content
	cat > ${tmp}

	# parse out the "To:" address
	to="`head -500 \"${tmp}\" | grep '^To:' | ${awk} '{print $2}'`"
	echo `basename $0`: to \"${to}\"

	# submit the message into the main spool directory
	content="`cat \"${tmp}\" | \"${sbin}emailrelay-submit\" --verbose --spool-dir \"${store}\" \"${to}\"`"
	envelope="`echo \"${content}\" | sed 's/content/envelope/'`"
	if test \! -f "${content}"
	then
		echo `basename $0`: emailrelay-submit failed >&2
		trap "" 0 # leave it in /tmp
		return
	fi

	# link & copy into subdirectories
	copied="0"
	for name in `List "${to}"` ""
	do
		if test "${name}" != ""
		then
			Create "${store}/${name}"

			c="${store}/${name}/`basename \"${content}\"`"
			e="${store}/${name}/`basename \"${envelope}\"`"

			ln "${content}" "${c}" && cp -p "${envelope}" "${e}"
			if test "$?" -ne 0 ; then return ; fi
			copied="1"
		fi
	done

	# delete from the main directory
	if test "${copied}" -eq 1
	then
		rm -f "${envelope}" && rm -f "${content}"
	fi
}

Main "$@" >> "${log}" 2>&1

