#!/bin/sh -

frompatt='/^From / && /\d:\d\d:\d\d/ && /\b\d{4}\b/'

winmail='tnef -wv'	# attempt to extract from any winmail.dat attachment

# pushmime - push messages or mboxes into subdirectories with their explosions
# Steve Kinzler, steve@kinzler.com, May 02/Oct 05
# https://kinzler.com/me/home.html#unix

type=; e=; bad=

while :
do
	case $# in
	0)	break;;
	*)	case "$1" in
		-m)	type=mime;;
		-b)	type=mbox;;
		-e)	e=-e;;

		--)	shift; break;;
		-h)	bad=t; break;;
		-*)	bad=t; echo "$0: unknown option ($1)" 1>&2;;
		*)	break;;
		esac
		shift;;
	esac
done

case "$#,$bad" in
0,*|*,t)	cat << EOF 1>&2
usage: $0 [ -e ] file ...
       $0 -m mimefile ...
       $0 -b [ -e ] mboxfile ...
	-m	push MIME messages into subdirs with their explosions
	-b	push mbox folders into subdirs with their messages
	-e	don't push each mbox message into a subdir with its explosion
Without -m or -b, single message files are run with -m and multi-message
files are run with -b.
EOF
		exit 1;;
esac

cwd=`pwd`					|| exit $?
num=$$

for arg
do
	case "$type" in
	mime|mbox)
		push -- "$arg" "$arg"		|| continue
		cd "$arg"			|| continue
		base=`echo "$arg" | sed 's/\/*$//; s/.*\///'`

		case "$type" in
		mime)	mimeexplode "$base"	|| continue
			pop -- "$base.d"
			test -n "$winmail" -a -f winmail.dat &&
				yes | $winmail winmail.dat;;

		mbox)	perl -pe "open(STDOUT, '>mbx-$num-' .
					       sprintf('%03d', ++\$n))
					if ! \$n || ($frompatt)" "$base"
			case "$e" in
			'')	pushmime -m mbx-"$num"-*;;
			esac;;
		esac

		cd "$cwd"			|| exit $?;;

	*)	perl -ne "\$n++ if $frompatt; END { exit \$n }" "$arg"
		case "$?" in
		[01])	pushmime -m    "$arg";;
		*)	pushmime -b $e "$arg";;
		esac;;
	esac
done
