#!/bin/sh
#
# Patch To: field in M.xxxxxxxx files
#
# This script looks for lines like:
# "in a msg Ben_Stuyts@p6.f202.n281.z2.fidonet writes"
# in the body of the message.
# It remembers the first one it finds.
# If the original "T" line in the header was to All,
# it will use the above name instead: Ben Stuyts.
#
# 02-feb-92 benst
# 13-may-92 benst more work...

# configure the following items:

# where are the temporary msg files stored:
MSG=/usr/spool/fnet/msg

# where is awk:
AWK=/usr/local/bin/mawk


# end of configuration part

for i in ${MSG}/M.????????
do
	echo Fixing $i...

	$AWK '
		BEGIN 	{	to_all_line = -1;
					receiver = "";
					i = 1;
				}
		
# save every line in msg buffer:
				{	msg[i] = $0;
					i++;
				}

# look for first line with valid "@" address in it:
		(receiver == "") && ($0 ~ /[A-Za-z_.]+@.*\.fidonet/)	{	
# find match for "Bla_bla.bla@bla.fidonet"
					m = match($0,/[A-Za-z_.]+@.*\.fidonet/);
					full_receiver = substr($0, RSTART, RLENGTH);
# now remove "@bla.fidonet"
					split(full_receiver, tmp, "@");
					receiver = tmp[1];
# substitute spaces for underscores:
					gsub(/_/, " ", receiver);
				}

# remember where "T All" line was:
		(to_all_line == -1) && $0 == "T All"	{
					to_all_line = NR;
				}

# finally, output msg with fixed "T" line
		END		{	for(j=1; j<i; j++) {
						if((j == to_all_line) && (receiver != "")) {
							print "T", receiver;
						} else {
							print msg[j];
						}
					}
				}
	' $i > /tmp/toconv_$$
	
	echo diff for /tmp/toconv_$$
	/bin/diff -B /tmp/toconv_$$ $i
	echo
	mv -f $i /tmp
	mv -f /tmp/toconv_$$ $i
done
