#!/bin/bash
# Determine the name of this service
service_name() {
    DIR=`dirname $0`
    pushd "${DIR}" > /dev/null
    TOP=`pwd | cut -d / -f 2`
    SERVICE=`pwd | cut -d / -f 3`
    popd > /dev/null
   
    # verify this is under the /srv mountpoint 
    if [ "${TOP-error}" = "srv" ]
    then
        echo $SERVICE
    else
        return 1;
    fi
}

# date-time-nanoseconds
DATE=`date +%Y%m%dT%H%M%S-%N`

# get the service name
SERVICE=`service_name $0`
ONSRV=$?

# If we are under /srv then continue
if [ $ONSRV -eq 0 ]
then
    # Write the follow to a log
    {
        echo From mailtrap@`hostname` `date`
        echo "Envelope-to: $@"
        echo "Delivery-date: "`date`
        cat
    }  > "/srv/${SERVICE}/var/spool/mail/${DATE}-${RANDOM}.log"

# otherwise just pretend like we're doing something
else
   echo err: not under /srv; mail output to /dev/null
   cat > /dev/null
   exit ${ONSRV-2}
fi

exit 0
