#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  email [-s SUBJECT] [-f FROM] [ADDRESS...] < BODY
		  email -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -s SUBJECT    the email subject (default: "CLI email: No subject")
		  -f FROM       the addr to send from (default: "eu@euandre.org")
		  -h, --help    show this message

		ADDRESS         the email addresses to send the email to (default: "eu@euandre.org")
		BODY            the text to be sent as the body


		Send an email to ADDRESS using BODY.


		Examples:

		  Send 10 numbers to mail@example.com:

		    $ seq 10 | email -s number mail@email.com


		  Send a UUID using all defaults:

		    $ uuid | email
	EOF
}

for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

FROM='eu@euandre.org'
SUBJECT='CLI email: No subject'
while getopts 'f:s:h' flag; do
	case "$flag" in
		(f)
			FROM="$OPTARG"
			;;
		(s)
			SUBJECT="$OPTARG"
			;;
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

ADDRESS="$(printf '%s\n' "$@" | tr '\n' ',' | sed 's|,|, |g;s|, $||')"


{
	cat <<-EOF
		Content-Type: text/plain; charset=UTF-8
		Content-Transfer-Encoding: 8bit
		From: $FROM
		To: ${ADDRESS:-eu@euandre.org}
		Subject: $(printf '%s' "$SUBJECT" | tr -d '\n')

	EOF
	cat -
} | sendmail -tf "$FROM"
