#! /usr/bin/env bash
set -e

# We require one argument (destination)
if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <destination>"
    exit 1
fi

# Read a list of all new mail
new_mail=$(mail -H 2> /dev/null | grep "^.N")
new_mail_count=$(echo "$new_mail" | wc -l | tr -d ' ')

# If this list is empty, exit
if [ -z "$new_mail" ]; then
    # echo "No new mail"
    exit 0
fi

# Make sure to mark all new mail as "unread" so we don't get in a loop.
echo "q" | mail -N > /dev/null

# Otherwise, we can continue to process the new mail
# NOTE: This line should be commented out for crons.
# echo "Found ${new_mail_count} new peices of mail"
echo -e "You have new mail waiting for you on $(hostname):\r\n\r\n${new_mail}" | mail -s "New mail on $(hostname)" "${1}"