# $Id: FirstRun.pm,v 1.4 2001/04/17 04:28:59 muhri Exp $
# -*- perl -*-
package Pronto::FirstRun;
use strict;
#use SelfLoader;
#1;
#__DATA__
my($sql,$query);
my %DriverVersions = ();

sub create_database {
 
 	my ($sql, $query);
 	mkdir($main::prefs{'MailDir'}, 0755);
 	mkdir("$main::prefs{'MailDir'}/sig", 0755);
	mkdir("$main::prefs{'MailDir'}/tmp", 0755);
	mkdir("$main::prefs{'MailDir'}/sessions",0755);
 	if ($main::prefs{'DatabaseDriver'} eq "CSV") {
  		$sql = "create table accounts (id int,
          		uname text, descr varchar(100), friendly varchar(100), smtp text, pop text,
          		pport int, pass text, reply text, include text, dm text, def text,
	  		type text, dupecheck text)";
  		$main::conn->do($sql) or die "Could not create table accounts\n";
  		$sql = "create table boxlist (id int,
          		name varchar(100), sibling int, parent int, query text, body text)";
  		$main::conn->do($sql) or die "Could not create table boxlist\n";
  		$sql = "create table filters (id int,
          		sorder int, type int, boxid int, regex text, addr text,
          		name varchar(100), trueregex int, count int )";
  		$main::conn->do($sql) or die "Could not create table filters\n";
  		$sql = "create table messages (id int, msgid varchar(255), boxid int, accountid int,
          		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, bcc text, sender text,
          		returnpath text, priority text, xmailer text, xuidl text, xsender text,
          		localdate text, newmsg text, replyf int, friendly text, rreceiptto text, score int,ref text,serverstat int)";
  		$main::conn->do($sql) or die "Could not create table Messages\n";
  		$sql = "create table bookmarks (id int, title text, url text)";
  		$main::conn->do($sql) or die "Could not create table Bookmarks\n";
  		$sql = "create table addresses (id int, alias text, address text,
          		public_key text, groups text)";
  		$main::conn->do($sql) or die "Could not create table Addresses\n";
		$sql = "create table groups (id int not null, name text not null)";
		$main::conn->do($sql) or die "Could not create table groups\n";
  		$sql = "create table mimetypes (id int, mime varchar(100), command varchar(100), icon varchar(100))";
 		$main::conn->do($sql) or die "Could not create table Mimestypes\n";

 	} elsif ($main::prefs{'DatabaseDriver'} eq "Pg") {
  		$sql = "create table accounts (id int4, 
          		uname text, descr text UNIQUE, friendly text, smtp text, pop
          		text, pport int4, pass text, reply text, include text, dm text,
          		def text, type text, dupecheck text)";
  		$main::conn->do($sql) or die "Could not create table accounts\n";
  		$sql = "create table boxlist (id int4,
          		name text UNIQUE, sibling int4, parent int4, query text, body text)";
  		$main::conn->do($sql) or die "Could not create table boxlist\n";
  		$sql = "create table filters (id int4,
          		sorder int4, type int4, boxid int4, regex text, addr text,
          		name text UNIQUE, trueregex int, count int)";
  		$main::conn->do($sql) or die "Could not create table filters\n";
  		$sql = "create table messages (id int4 PRIMARY
          		KEY, msgid text, 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, bcc text, sender text,
          		returnpath text, priority text, xmailer text, xuidl text, xsender text,
          		localdate text, newmsg text, replyf int4, friendly text, rreceiptto text, score int4, ref text,serverstat int4)";
  		$main::conn->do($sql) or die "Could not create table Messages\n";
  		$sql = "create table bookmarks (id int4, title text, url text)";
  		$main::conn->do($sql) or die "Could not create table Bookmarks\n";
  		$sql = "create table addresses (id int, alias text, address text,
          		public_key text, groups text)";
  		$main::conn->do($sql) or die "Could not create table Addresses\n";
		$sql = "create table groups (id int not null, name text)";
		$main::conn->do($sql) or die "Could not create table groups\n";
  		$sql = "create table mimetypes (id int4, mime text, command text, icon text)";
  		$main::conn->do($sql) or die "Could not create table Mimetypes\n";
 		$sql = "create table message_sources (id int4 PRIMARY KEY, bodytext TEXT)";
		$main::conn->do($sql) or die "Could not create table message_sources\n";
	} elsif ($main::prefs{'DatabaseDriver'} eq "mysql") {
  		$sql = "create table accounts (id int4 PRIMARY KEY,
          		uname text, friendly varchar(100), descr varchar(100) NOT NULL, smtp text, pop text,
          		pport int4, pass text, reply text, include text, dm text, def text,
          		type text, dupecheck text, UNIQUE descr (descr))";
  		$main::conn->do($sql) or die "Could not create table accounts\n";
  		$sql = "create table boxlist (id int4 PRIMARY KEY,
          		name varchar(100) NOT NULL, sibling int4, parent int4,
          		UNIQUE name (name), query text, body text)";
  		$main::conn->do($sql) or die "Could not create table boxlist\n";
  		$sql = "create table filters (id int4 PRIMARY KEY,
          		sorder int4, type int4, boxid int4, regex text, addr text,
          		name varchar(100) NOT NULL, UNIQUE name (name), trueregex int, count int)";
  		$main::conn->do($sql) or die "Could not create table filters\n";
  		$sql = "create table messages (id int4 PRIMARY KEY
          		,msgid varchar(255), 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, bcc text,sender text,
          		returnpath text, priority text, xmailer text, xuidl text, xsender text,
          		localdate text, newmsg text, replyf int4, friendly text, rreceiptto text, score int4, ref text,serverstat int4)";
  		$main::conn->do($sql) or die "Could not create table Messages\n";
  		$sql = "create table bookmarks (id int4, title text, url text)";
  		$main::conn->do($sql) or die "Could not create table Bookmarks\n";
  		$sql = "create table addresses (id int4, alias text, address text,
          		public_key text, groups text not null)";
  		$main::conn->do($sql) or die "Could not create table Addresses\n";
		$sql = "create table groups (id int not null, name text)";
		$main::conn->do($sql) or die "Could not create table groups\n";
  		$sql = "create table mimetypes (id int4, mime text, command text, icon text)";
  		$main::conn->do($sql) or die "Could not create table Mimetypes\n";
 		$sql = "create table message_sources (id int4 PRIMARY KEY, bodytext longtext)";
		$main::conn->do($sql) or die "Could not create message_sources table\n";
	} else { 
		die "I don't know how to make your tables...\nPlease make them manually using the source code from lines 916 through 942 as an example.\n"; 
	}
  	$sql= "insert into boxlist (id, name, sibling, parent) values (?, ?, ?,
		?)";
  	$query=$main::conn->prepare($sql);
  	$query->execute(0, "Folders", 65535, -1) or die "Could not insert Master Folder\n";
  	$query->execute(1, "Inbox", 2, 0) or die "Could not insert Inbox\n";
  	$query->execute(2, "Outbox", 3, 0) or die "Could not insert Outbox\n";
  	$query->execute(3, "Sent Items", 4, 0) or die "Could not insert Sent Items\n";
  	$query->execute(4, "Deleted Items", 5, 0) or die "Could not insert Deleted Items\n";
  	$query->execute(5, "Drafts", 1000, 0) or die "Could not insert Drafts\n";
  	$query->execute(1000, "Search", 65535, 0) or die "Could not insert Search\n";
  
	return 1;
}



sub firstSetup {
	my ($setup_win,$window,$bg,$tbox,$hbox,$sep, $butbox,$ok,$cancel,$pixmap);
	my @dbidrivers=({'drvname'=>'CSV','installed'=>0},
			{'drvname'=>'mysql','installed'=>0},
			{'drvname'=>'Pg','installed'=>0});
	$setup_win = new Gtk::Window("dialog");
	$setup_win->set_title(_("Pronto - Database Setup..."));
	$setup_win->signal_connect("destroy" => sub { $setup_win->destroy; });
	$setup_win->signal_connect("delete_event" => \&Gtk::false);
	$setup_win->border_width('2');
	$setup_win->position(-mouse);
	$setup_win->set_default_size('350','450');
	$setup_win->set_policy(1,1,0);
	$setup_win->show;
	$window = $setup_win->window;
	$bg = $setup_win->style->bg('normal');
	$hbox= new Gtk::VBox(0,0);
	$setup_win->add($hbox);
	$hbox->show;
	$pixmap = &main::new_pixmap("$main::prefs{'PixmapDir'}/about.xpm", $window, $bg);
	$pixmap->show;
	$hbox->pack_start($pixmap,1,1,1);   
	$setup_win->{'label'}=new Gtk::Label(_("Pronto Database Setup"));
	$setup_win->{'label'}->set_alignment(0.5,0.5);
	$hbox->pack_start($setup_win->{'label'},1,0,1);   
	$setup_win->{'label'}->show;
	my ($tmp,$errmessage, $supportlist);
	# test for DBI
	my $dbiinstalled=0;
	my $installed=0;
	$tmp="use DBI;";
	eval $tmp; $dbiinstalled=1 unless $@;
	for(my $i=0;$i<scalar(@dbidrivers);$i++){
		# test for the dbi dirvers
		$tmp="use DBD::".$dbidrivers[$i]{'drvname'}.";";
		eval $tmp; $dbidrivers[$i]{'installed'}=1 unless $@;
		$supportlist.=$dbidrivers[$i]{'drvname'}." ";
		$installed=1 if $dbidrivers[$i]{'installed'};
		my $d = "DBD::$dbidrivers[$i]{'drvname'}";
		$DriverVersions{$dbidrivers[$i]{'drvname'}} = $d->VERSION() if $dbidrivers[$i]{'installed'};
	}

	# we found something?
	if ($installed && $dbiinstalled){
		$setup_win->{'flabel'}=new Gtk::Label(_("Please select your driver from the list below:\nNote that CSV does not need\n a username or a password"));
		$setup_win->{'flabel'}->set_alignment(0.5,0.5);
		$hbox->pack_start($setup_win->{'flabel'},1,1,1);   
		$setup_win->{'flabel'}->show;
		$setup_win->{'select'}=new Gtk::Combo;
		$setup_win->{'select'}->set_case_sensitive(1);
		$setup_win->{'select'}->set_usize(25,25);
		my @drvlist;
		for(my $i=0;$i<scalar(@dbidrivers);$i++){
			push (@drvlist, $dbidrivers[$i]{'drvname'}) if $dbidrivers[$i]{'installed'};
		}
		$setup_win->{'select'}->set_popdown_strings(@drvlist);
		$setup_win->{'select'}->popwin->signal_connect("hide" =>\&show_more_options, $setup_win);
		$setup_win->{'select'}->entry->set_editable(0);
		$setup_win->{'select'}->show;
		$hbox->pack_start($setup_win->{'select'},1,0,1);   
		
		my ($hb1,$hb2,$l1,$l2);
		$hb1=new Gtk::HBox(0,0);
		$l1=new Gtk::Label(_("DB Username:"));
		$l1->set_alignment(0.0,0.5);
		$l1->set_usize(90,10);
		$hb1->pack_start($l1, 0,0,5);
		$l1->show();
		$setup_win->{'user'}=new Gtk::Entry;
		$hb1->pack_start($setup_win->{'user'},0,0,5);
		$setup_win->{'user'}->show;
		$hbox->pack_start($hb1,0,0,0);
		$hb1->show;
		$hb2=new Gtk::HBox(0,0);
		$l2=new Gtk::Label(_("DB Password:"));
		$l2->set_usize(90,10);
		$l2->set_alignment(0.0,0.5);
		$hb2->pack_start($l2, 0,0,5);
		$l2->show();
		$setup_win->{'pw'}=new Gtk::Entry;
		$hb2->pack_start($setup_win->{'pw'},0,0,5);
		$setup_win->{'pw'}->set_visibility(0);
		$setup_win->{'pw'}->show;
		$hbox->pack_start($hb2,0,0,0);
		$hb2->show;
		$setup_win->{'hostlabel'} = new Gtk::Label(_("Database Host:"));
		$setup_win->{'hostlabel'}->set_alignment(0.0,0.5);
		$setup_win->{'hostlabel'}->set_usize(90,10);
		$setup_win->{'host'} = new Gtk::Entry;
		$setup_win->{'host'}->set_text("localhost");
		$setup_win->{'portlabel'} = new Gtk::Label(_("Database Port:"));
		$setup_win->{'portlabel'}->set_alignment(0.0,0.5);
		$setup_win->{'portlabel'}->set_usize(90,10);
		$setup_win->{'port'} = new Gtk::Entry;
		$setup_win->{'port'}->set_text("3306");
		$setup_win->{'MsgInDB'} = new Gtk::CheckButton();
	        $setup_win->{'storeindb'} = new Gtk::Label(_("Store Messages in DB?"));
		$setup_win->{'storeindb'}->set_alignment(0.0,0.5);		
		my $portbox = new Gtk::HBox(0,0);
		$portbox->pack_start($setup_win->{'portlabel'},0,0,5);
		$portbox->pack_start($setup_win->{'port'},0,0,5);
		$portbox->show();
		my $hb3 = new Gtk::HBox(0,0);
		$hb3->pack_start($setup_win->{'hostlabel'},0,0,5);
		$hb3->pack_start($setup_win->{'host'},0,0,5);
		$hb3->show();
		$setup_win->{'hostlabel'}->show;
		$setup_win->{'storeindb'}->show;
		my $hb4 = new Gtk::HBox(0,5);
		$hb4->pack_start($setup_win->{'MsgInDB'},0,0,0);
		$hb4->pack_start($setup_win->{'storeindb'},0,0,0);
		$hb4->show();
		$hbox->pack_start($hb3,0,0,0);
		$hbox->pack_start($portbox,0,0,0);
		$hbox->pack_start($hb4,0,0,5);
		} else {
		# we have no driver found, show message
		if (!$dbiinstalled){
			$errmessage=_("DBI not found. Install it from CPAN (www.cpan.org). \nGet there your favorite DBD driver too.");
		} else {
			$errmessage=_("No supported DBD driver ($supportlist) found.\nPlease get one for your db system at CPAN.\nIf you don't have any database installed get the DBD::CSV \nmodule.If you use a unsupported driver, please\ncontact Pronto\@muhri.net");
		}
		$setup_win->{'errlabel'}=new Gtk::Label($errmessage);
		$setup_win->{'errlabel'}->set_alignment(0.5,0.5);
		$hbox->pack_start($setup_win->{'errlabel'},1,1,1);   
		$setup_win->{'errlabel'}->show;
	}
	$sep = new Gtk::HSeparator;
	$sep->set_usize(-1,5);
	$hbox->pack_start($sep,0,1,0);
	$sep->show;

	$butbox = new Gtk::HButtonBox;
	$butbox->set_usize(-1,32);
	$hbox->pack_start($butbox, 0,1,0);
	$butbox->show;

	if ($installed){	
		$ok = new_with_label Gtk::Button(_("OK"));
		$ok->set_usize(50,-1);
		$ok->signal_connect('clicked', \&testSetup, $setup_win);
		$ok->can_default(1);
		$ok->grab_default;
		$butbox->add($ok);
		$ok->show;
	}

	$cancel = new_with_label Gtk::Button(_("Cancel"));
	$cancel->set_usize(50,-1);
	$cancel->signal_connect('clicked', sub { $setup_win->destroy; Gtk->exit(0);});
	$cancel->can_default(1);
	$cancel->grab_default;
	$butbox->add($cancel);
	$cancel->show;
	if ($installed) {
		&show_more_options($setup_win->{'select'},$setup_win);
	}
}

sub testSetup {
	my ($widget, $win)=@_;
	my ($tmp);
	my $error=0;
	$main::prefs{'DatabaseDriver'}=$win->{'select'}->entry->get_text;
	$main::prefs{'DatabaseUser'}=$win->{'user'}->get_text;
	$main::prefs{'DatabasePassword'}=$win->{'pw'}->get_text;
	$main::prefs{'DatabaseHost'}=$win->{'host'}->get_text;
	#port 
	
	if ($main::prefs{'DatabaseDriver'} eq "mysql") {
		$main::prefs{'MySQLPort'}=$win->{'port'}->get_text;
	} elsif ($main::prefs{'DatabaseDriver'} eq "Pg") {
		$main::prefs{'PgSQLPort'}=$win->{'port'}->get_text;
	}
	
	if ($win->{'MsgInDB'}->active) { 
		$main::prefs{'MsgInDB'} = "y"; 
       	} else { 
		$main::prefs{'MsgInDB'} = "n"; 
       	}
	
	if ($main::prefs{'MsgInDB'} eq "y" && 
	    $main::prefs{'DatabaseDriver'} eq "Pg" &&
	    $DriverVersions{'Pg'} < 0.96) {
	    	&main::err_dialog(_("Your DBD::Pg version is less than 0.96 which is the required version for storing messages in the database for PostgreSQL, turning MsgInDB off"));
		$main::prefs{'MsgInDB'} = "n";
	}	
	
	$tmp='$main::conn=&main::open_db_conn(1)';
	eval $tmp or $error=1;
	if ($error){
		# unable to open the db itself
		&main::err_dialog(_("Please go back to the setup dialog:") ."\n $DBI::errstr");
		$tmp="$DBI::errstr";
	} else {
		# now let's do a select...
		$sql = "select * from accounts";
		$query = $main::conn->prepare($sql);
		$query->execute() or $error=1;
		if ($error){
			$win->{'flabel'}->set_text(_("Creating tables..."));
			&create_database;
		} 
		#create dirs in case its a reinstall with an old db.
		mkdir($main::prefs{'MailDir'}, 0755);
	 	mkdir("$main::prefs{'MailDir'}/sig", 0755);
		mkdir("$main::prefs{'MailDir'}/tmp", 0755);
		mkdir("$main::prefs{'MailDir'}/sessions", 0755);
		$win->destroy;
		&main::appInit();
	}
	return 1;
}

sub show_more_options 
{
	my ($widget, $win) = @_;	
	my $driver = $win->{'select'}->entry->get_text();
	if ($driver ne "CSV") {
		$win->{'host'}->show;
		$win->{'MsgInDB'}->show;
		$win->{'hostlabel'}->show;
		$win->{'storeindb'}->show;
		$win->{'portlabel'}->show;
		$win->{'port'}->show;
		$win->{'port'}->set_text("3306") if $driver eq "mysql";
		$win->{'port'}->set_text("5432") if $driver eq "Pg";
	} else {
		$win->{'host'}->hide;
		$win->{'MsgInDB'}->hide;
		$win->{'hostlabel'}->hide;
		$win->{'storeindb'}->hide;
		$win->{'portlabel'}->hide;
		$win->{'port'}->hide;
	}			
}	

1;
