#!/bin/bash
#
# by: Brian Butler (20100921)
#
# Grading script for the email lab
# this script is to be installed and run on desktopX.example.com
# output is logged to syslog

# Set environment and declare global variables
. /usr/local/lib/labtool.shlib
trap on_exit EXIT
LOG_FACILITY=local0
LOG_PRIORITY=info
LOG_TAG=emailLab
DEBUG=false
ERROR_MESSAGE="Error running script. Contact your instructor if you continue to see this message."
PATH=/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin
userInput="no"
set -o pipefail
stationNum="$(hostname | grep -o "[0-9]*")"
domainName="domain${stationNum}.example.com"

# Check to make sure we are running as root
check_root

# Check to make sure we are running on the correct host
check_host "desktop"

sshKey="/root/.ssh/.labtoolkey"
#sshKey="/root/.ssh/id_rsa"

# if key exists, use it, otherwise just ssh
if [ -f $sshKey ]; then
	SSH="ssh -i $sshKey"
else
	SSH="ssh"
fi

# Create elvis user for testing
id elvis > /dev/null || useradd elvis
$SSH root@server${stationNum}.example.com "id elvis || useradd elvis" || exit 1

# Check that elvis@domainX.example.com receives external email
echo
echo -n "Checking that email to domain${stationNum}.example.com is received... "
echo $domainName > /tmp/domainName

# Send an email to domainX through instructor's smtp relay
(env MAILRC=/dev/null from="grading.${domainName}@example.com" smtp="instructor.example.com" mail -s "lab-grade-email -- TESTING EXTERNAL EMAIL" elvis@$domainName </tmp/domainName 2>&1 | log) || exit 1

# Check that mail.domainX.example.com received the email from instructor
ERROR_MESSAGE="FAILED."
($SSH root@server${stationNum}.example.com cat /var/spool/mail/elvis | grep "^Subject: lab-grade-email -- TESTING EXTERNAL EMAIL$" &> /dev/null) || exit 1
echo "PASSED."

# Check that desktop sends email through smtp.domainX.example.com to mail.domainX.example.com
# this still needs work...

# echo
# echo -n 'Checking that desktop sends email through smtp.domain${stationNum}.example.com... '
# (su -l elvis -c 'echo "testing" | mail -s "lab-grade-email -- TESTING INTERNAL EMAIL" elvis@$domainName' 2>$1 | log) || exit 1
# (ssh -i $sshKey root@server${stationNum}.example.com cat /var/spool/mail/elvis | grep "^Subject: lab-grade-email -- TESTING INTERNAL EMAIL$" &> /dev/null) || exit 1
# echo "PASSED."

echo
echo 'Lab Successfully Completed!'
exit 0
