#!/usr/bin/perl
use File::Copy;
require "prontolib.pl";
&read_prefs();
$conn=&open_db_conn;
print("Hi, this may take a minute depending on your db driver \nAdding the references field\n");
&add_refs;
print("Adding Filter count field\n");
&add_filtercount;
print("I'm done :)\n");
sub add_refs 
{
	if ($prefs{'DatabaseDriver'} eq "CSV") {
		&add_csv_column("$prefs{'MailDir'}/messages","ref");
	}
	if ($prefs{'DatabaseDriver'} eq "mysql" or $prefs{'DatabaseDriver'} eq "Pg") {
		if ($prefs{'DatabaseDriver'} eq "mysql") {
			$sql = "alter table messages add ref text;";
		} else {
			$sql = "alter table messages add column ref text";
		}
		$query=$conn->prepare($sql);
		$query->execute();
		
	}	
	$sql = "select id from messages";
	$query= $conn->prepare($sql);
	$query->execute();
	$count = 0;

	while (($msgid) = $query->fetchrow_array()) {
		$tmp = &filename_to_tree("$prefs{'MailDir'}/$msgid");
		open(TMP,"<$tmp");
		while (<TMP>) {
			if (/^References:\s*(.+)/i) {
				print ("Message: $msgid has ref $1 \n");
				$sql = "update messages set ref = '$1' where id = '$msgid'";
				$conn->do($sql);
				$count++
			}
		}	
		close(TMP);
	}
print $count . " messages have been updated with refs \n";
}


sub add_filtercount
{
	if ($prefs{'DatabaseDriver'} eq "mysql") {
		$sql = "alter table filters add count int";
	} elsif ($prefs{'DatabaseDriver'} eq "Pg") {
		$sql = "alter table filters add column count int";
	} elsif ($prefs{'DatabaseDriver'} eq "CSV") {
		&add_csv_column("$prefs{'MailDir'}/filters","count");
	}	
	$query = $conn->prepare($sql);
	$query->execute();
	$sql = "update filters set count = '0'";
	$conn->do($sql);
}

sub add_csv_column
{
	my ($filename, $column) = @_;
	open (FILE, $filename);
	@file = <FILE>;
	close (FILE);
	$columnlist = $file[0];
	if ($columnlist =~ m/\b$column\b/) { print "has been added already\n"; return 1; }
	if ($column eq "ref") {
		$columnlist=~ s/,score/,score,ref/i;
	} elsif ($column eq "count") {
		$columnlist=~ s/,name/,name,count/i;
	}
	$file[0] = $columnlist;
	copy($filename,$filename."_bak");
	open(FILE,">$filename");
	foreach(@file) { print FILE $_  }
	close(FILE);
}
