#!/usr/bin/perl

# This program is intended to migrate a CSCMail v1.2 or lower database
# to the new v1.3 format.  If you are doing a brand new install of
# v1.3 and do not have a v1.2 message store, you do NOT need to run
# this script.
# 
# This script WILL not migrate from one backend to another.
# it is designed exclusively to alter the database structure for
# Postgres users who upgraded from pre 1.3 to the 1.3.x series of
# CSCMail.

use Postgres;

$user = $ENV{USER};

$conn=db_connect($user);

mkdir("/home/$user/.cscmail");
$sql = "create sequence msgid;";
$query=$conn->execute($sql);
$sql = "create table msgnew (id int4 default nextval('msgid') PRIMARY
         KEY, msgid text UNIQUE, boxid int4, accountid int4,
         date text, sentto text, sentfrom text, subject text, contenttype text,
         contentxferencode text, mimeversion text, precedence text,
         approvedby text, inreplyto text, replyto text, listsub text,
         listunsub text, status text, xorigip text, cc text, sender text,
         returnpath text, priority text, xmailer text, xsender text,
         localdate text, newmsg text);";
$query=$conn->execute($sql) or die "Could not create table msgnew\n";
$sql = "select * from messages;";
$query=$conn->execute($sql) or die "ERROR: $Postgres::error\mUnable to
select old messages\n";
while (@row=$query->fetchrow()) {
 foreach (@row) {
  $_ = quotemeta($_);
 }
 $sql2 = "insert into msgnew (msgid, boxid, accountid, date, sentto,
sentfrom, subject, contenttype, contentxferencode, mimeversion,
precedence, approvedby, inreplyto, replyto,
listsub, listunsub, status, xorigip, cc, sender, returnpath, priority,
xmailer, xsender, localdate) values
(\'$row[0]\', $row[1], $row[2], \'$row[3]\', \'$row[4]\', \'$row[5]\',
\'$row[6]\', \'$row[7]\', \'$row[8]\', \'$row[9]\', \'$row[10]\',
\'$row[11]\', \'$row[12]\', \'$row[13]\', \'$row[14]\', \'$row[15]\',
\'$row[16]\', \'$row[17]\', \'$row[18]\', \'$row[19]\', \'$row[20]\',
\'$row[21]\', \'$row[22]\', \'$row[23]\', \$row[26]\');";
 $query2 = $conn->execute($sql2) or die "ERROR: $Postgres::error\nUnable
to import message to new table\n";
 $sql2 = "select id from msgnew where msgid = \'$row[0]\';";
 $query2=$conn->execute($sql2);
 $row2=$query2->fetchrow();
 open(TMP,">/home/$user/.cscmail/$row2[0].hdr");
 print TMP $row[24];
 close(TMP);
 $sql2="select lo_export(messages.rawmime,
\'/home/$user/.cscmail/$row2[0].msg\') from messages where id =
\'$row[0]\';";
 $query2=$conn->execute($sql2) or die "ERROR: $Postgres::error\nUnable to 
save large object to new file\n";
}
$sql = "drop table messages;";
$query = $conn->execute($sql) or die "ERROR: $Postgres::error\nUnable to
drop old message table\n";
$sql = "alter table newmsgs rename to messages;";
$query = $conn->execute($sql) or die "ERROR: $Postgres::error\nUnable to
rename new message table\n";
print "Conversion complete.\n";
