#! /bin/sh
# $Header: /u3/acs/jdpeek/.bin/RCS.Z/babyl2mh,v 1.1 90/03/22 03:57:05 jdpeek Exp $
###	babyl2mh - slow way to convert Emacs Rmail files to MH
###	Usage: babyl2mh +mh-folder [RMAIL-FILE]

#	NOTE: PROGRAM HASN'T BEEN TESTED THOROUGHLY.
# 	CHECK THE MESSAGES!
#	Placed in the public domain.  Use at your own risk.
#		--Jerry Peek, 22 March 1990

dfltprot=600	# DEFAULT MESSAGE PROTECTION (IF NONE IN MH PROFILE)
folopts="-fast -nolist -nototal -nopack -norecurse"
mh=/usr/local/mh
mhprofile=/u3/acs/jdpeek/.bin/mhprofile	# READS MH PROFILE
scanopts="-noclear -noheader -noreverse"

case "$1" in
[@+]?*)
	# IF $1 DOESN'T EXIST, folder WILL CREATE IT (SIGH).
	# THAT'S BECAUSE stdout IS REDIRECTED AWAY FROM TERMINAL.
	if $mh/folder $folopts "$1" >/dev/null
	then
		# GET PATHNAME OF FOLDER, LAST MESSAGE NUMBER:
		folpath="`$mh/mhpath`" || exit
		firstmsg="`$mh/scan -format '%(msg)' last`" || exit
	else
		echo "`basename $0`: no folder.  quitting." 1>&2
		exit 1
	fi
	;;
*)	echo "Usage: `basename $0` +folder|@folder [file]
	('$1' doesn't start with + or @.)" 1>&2
	exit 1
	;;
esac

if [ -n "$2" -a \( ! -r "$2" \) ]
then
	echo "`basename $0`: quitting: can't read Rmail file '$2'." 1>&2
	exit 1
fi

# GET PROTECTION MODE FROM MH PROFILE (IF NONE, USE $dfltprot):
msgprot="`$mhprofile -b msg-protect`" || msgprot=$dfltprot

# MAKE SHELL ARCHIVE FILE ON awk'S STANDARD OUTPUT.
# PIPE IT INTO sh TO CREATE THE MESSAGE FILES...
awk "BEGIN {
	folpath=\"$folpath\" # STORE AS STRING, WITH QUOTES
	msgprot=$msgprot     # STORE AS NUMBER (NO QUOTES)
	msgnum=$firstmsg"'   # CHANGE FROM DOUBLE- TO SINGLE-QUOTES
	gotflags=0
	gotgoodhdr=0
	gotbadhdr=0
}
# SKIP BABYL HEADER:
NR==1, /\037\014/ {
	next
}
# PROCESS MESSAGES.  USE gotflags, ETC. TO "REMEMBER"
# WHEN WE HAVE PASSED EACH PART OF EACH MESSAGE.
{
	# MESSAGE ENDS WITH CTRL-UNDERSCORE AT START OF A LINE.
	# PRINT SHELL COMMANDS AND RESET FLAGS:
	if ($0 ~ /^\037/) {
		printf "END-OF-%s/%d\n\n", folpath, msgnum
		# SET PROTECTION (INEFFICIENT; SHOULD DO ALL MSGS. AT ONCE)
		printf "chmod %d %s/%d\n", msgprot, folpath, msgnum
		gotflags = 0
		gotgoodhdr = 0
		gotbadhdr = 0
		next
	}
	# INSTEAD OF FLAGS LINE (LIKE "1,,"), PRINT START OF ARCHIVE:
	if (gotflags == 0) {
		gotflags = 1
		msgnum += 1
		printf "/bin/cat > %s/%d << \\END-OF-%s/%d\n", \
			folpath, msgnum, folpath, msgnum
		next
	}
	# PRINT THE FULL HEADER (UP TO FIRST BLANK LINE):
	if (gotgoodhdr == 0) {
		if ($0 !~ /^$/) {
			print
			next
		}
		else {
			gotgoodhdr = 1
			next
		}
	}
	# SKIP THE SHORT HEADER (UP TO NEXT BLANK LINE):
	if (gotbadhdr == 0 && $0 !~ /^$/)
		next
	gotbadhdr = 1
	# PRINT THE MESSAGE (UP TO ^_):
	print
	next
}' $2 |
/bin/sh -e	# EXIT ON ANY ERROR

exit # RETURN STATUS FROM PIPE ABOVE
