#!/bin/sh

#
# $VER: freebsd2mysql.sh 0.9 (24.12.2003) Riccardo "VIC" Torrini
#


# archive base
k=/usr/local/minimalist/ml-abuse/archive
test -d ${k} || mkdir -p ${k}
cd ${k}

now=`date "+%Y/%m/%d/%H:%M:%S".$$`
awk -vout="${now}" 'BEGIN {
	split(out, a, "/");
	p = sprintf( "%s/%s/%s", a[1], a[2], a[3] );
	s = sprintf( "test -d %s || mkdir -p %s", p, p );
	system(s);
}'
tee ${now} | awk -vout="${now}" -vml="${1}" '
/^Subject: / { $1 = ""; subj = substr($0, 2); }
/^From: / { $1 = ""; from = substr($0, 2); }
/^Date: / { $1 = ""; date = substr($0, 2); }
/^Sender: / { $1 = ""; safe = substr($0, 2); }
/^X-No-Archive: / { $1 = ""; noArchive = tolower(substr($0, 2)); }

/^$/ {
	RS = "\0";
	getline;
	body = $0;
}

END {
	gsub("\\\\", "\\\\", subj);
	gsub("\\\\", "\\\\", from);
	gsub("\\\\", "\\\\", body);
	s = sprintf( "%c", 34);
	r = sprintf( "\\%c", 34);
	gsub(s, r, subj);
	gsub(s, r, from);
	gsub(s, r, body);
	z = sprintf( "%c", 26);
	gsub(z, "", body);
	month["Jan"] = 1;
	month["Feb"] = 2;
	month["Mar"] = 3;
	month["Apr"] = 4;
	month["May"] = 5;
	month["Jun"] = 6;
	month["Jul"] = 7;
	month["Aug"] = 8;
	month["Sep"] = 9;
	month["Oct"] = 10;
	month["Nov"] = 11;
	month["Dec"] = 12;
#---
# Date: Wed, 24 Dec 2003 15:47:09 +0100
# Date: 24 Dec 2003 15:47:09 +0100
#---
	split(date, field);
	n = split(field[5], t, ":");
	if (n == 1) {
		m = split(field[4], t, ":");
		if (m > 0) {
			timestamp = sprintf("%04d%02d%02d%02d%02d%02d",
				field[3], month[field[2]], field[1], t[1], t[2], t[3] );
		}
	} else {
		timestamp = sprintf("%04d%02d%02d%02d%02d%02d",
			field[4], month[field[3]], field[2], t[1], t[2], t[3] );
	}
	if ( tolower(safe) == "owner-" ml "@freebsd.org" && noArchive != "yes" ) {
		s = sprintf( "rm -f %s", out );
		system(s);
		newML = ml;
		gsub("freebsd-", "ml_FreeBSD_", newML);
		printf( "INSERT INTO %s(head, name, body, data) " \
			"VALUES(\"%s\", \"%s\", \"%s\", \"%s\");\n",
				newML, subj, from, body, timestamp );
	} else {
		s = sprintf( "mv %s %s_%s", out, out, ml );
		system(s);
		# a dummy line to make mysql happy ;^)
		printf( "select null from faq;\n" );
	}
}' | /usr/local/bin/mysql -uroot -pm4ndrak3 --database=gufiwebdb
