#! /bin/sh

# This code is in the public domain
# Written by Robbert Haarman

boundary="mail_parts_boundary"
mailer='post-message'
message=
recipient=
sender="$USER@`hostname`"
subject="Message from mail-parts"
if [ -n "$TMPDIR" ];
then
	tmpfile="$TMPDIR/mail-parts-$$"
else
	tmpfile="/tmp/mail-parts-$$"
fi
headers_sent=

## Parse command line
while [ $# -gt 0 ]
do
	case "$1" in
	-b|--boundary)
		shift
		boundary="$1"
	;;
	-f|--from)
		shift
		sender="$1"
	;;
	-m|--mailer)
		shift
		mailer="$1"
	;;
	-s|--subject)
		shift
		subject="$1"
	;;
	-t|--to)
		shift
		recipient="$1"
	;;
	-*)
		echo "Unknown option: $1" >&2
		exit 128
	;;
	*)
		if [ -z "$recipient" ]
		then
			echo "No recipient specified!" 2>&1
			exit 128
		fi

		if [ -z "$headers_sent" ]
		then
			printf 'Subject: %s\015\012' "$subject"
			printf 'From: %s\015\012' "$sender"
			printf 'To: %s\015\012' "$recipient"
			printf 'Date: %s\015\012' "`date`"
			printf 'Content-Type: multipart/mixed; boundary="%s"\015\012' \
				"$boundary"
			printf '\015\012'
			headers_sent=true
		fi
		printf '\015\012--%s\015\012' "$boundary"
		cat "$1"
	esac
	shift
done > "$tmpfile"
printf '\015\012--%s--\015\012' "$boundary" >> "$tmpfile"

"$mailer" -f "$sender" "$recipient" < "$tmpfile"
rm "$tmpfile"
