#! /bin/sh

# convert mailboxes to maildirs

for f in "$@"; do
	echo -n $f

	test ! -f "$f" && echo ": not a mbox" && continue

	# create destination Maildir
	DIR="$f.$$"
	mkdir "$DIR" "$DIR"/cur "$DIR"/new "$DIR"/tmp
	chmod u=rwx,go= "$DIR" "$DIR"/cur "$DIR"/new "$DIR"/tmp
	touch "$DIR/maildirfolder"

	# split mbox into messages in maildir
	awk -v DIR="$DIR" -v PID=$$ -v HOST=`hostname` '
		function nextmsg() {
			if (header != "") {
				close(DIR"/tmp/msg")
				"fstat -disa \""DIR"/tmp/msg\"" | getline fstat
				close("fstat -disa \""DIR"/tmp/msg\"")
				split(fstat, f)
				out = sprintf("%d.M0P%dV%04XI%08X.%s,S=%d:2,%s", f[4], PID, f[1], f[2], HOST, f[3], (read ? "S" : ""))
				system("mv \""DIR"/tmp/msg\" \""DIR"/cur/"out"\"")
				read = 0
				printf "."
			}
		}
		/^From / { nextmsg(); header = 1; next }
		/^Status: R/ && header == 1 { read = 1 }
		/^$/ { header = 0 }
		/^>[Ff]rom / { sub("^>", "") }
		{ print > DIR"/tmp/msg" }
		END { nextmsg() }' "$f" &&
	rm -f "$f" &&
	mv "$DIR" "$f"
	echo
done
