#!/usr/bin/perl -w
#
# bin/agnctl
# Agnostos Control Utility (database installation, backup, restore)
# 
# Bozhin Zafirov (bozhin@abv.bg)
#
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (GPL). If you
# did not receive this file, see http://www.gnu.org/licenses/gpl.txt.
#


use strict;

use CGI;
use Getopt::Std;
use MIME::Base64;
use POSIX qw(strftime);


# Load libraries
use lib "..";
use core::Config;
use core::Syslog;
use core::FileIO;
use core::Language;
use core::HTML;
use core::MySQL;


# Objects container
my %object;

# Create objects
$object{config}   = new core::Config();
$object{syslog}   = new core::Syslog(%object);
$object{fileio}   = new core::FileIO(%object);
$object{language} = new core::Language(%object);
$object{html}     = new core::HTML(%object);
$object{mysql}    = new core::MySQL(%object);

# Database backup directory
my $backupdir = $object{config}->Get('AppRootDir')."db_backup";

# Create database directory if it does not exist
if (! -d $backupdir) {
	mkdir $backupdir || die "Can't create backup directory, goodbye!";
}


# Commandline options
my %option;
# Get options
getopts('br:RIlLOitsScd:p:H:D:U:P:hGA', \%option);



sub PrintHelp {
	# Prepare help
	my %options = (
		'b'		=> "backup database (can't be used in conjunction with -r)",
		'r'		=> "restore database from a previous backup (can't be used in conjunction with -b)",
		'R'		=> "restore last previously backed up database (can't be used in conjunction with -b)",
		'l'		=> "list available backups",
		'L'		=> "list last available backup",
		'O'		=> "list first available backup (oldest)",
		's'		=> "silent execution of the script (for use with -b or -r)",
		'c'		=> "create database structure (intended for installation of agnostos)",
		'i'		=> "initial database data inserts (intended for installation of agnostos)",
		'I'		=> "do a fresh database install (same as -c -i)",
		'S'		=> "set database parametters in config file (for use in conjuction with -H, -D, -U, -P and -p)",
		't'		=> "insert TRUNCATE TABLE before restore (for use in conjuction with -r and -R)",
		'd <num>'	=> "delete a backup database copy",
		'H <address>'	=> "database host address (default from config.xml)",
		'D <dbname>'	=> "database name (default from config.xml)",
		'U <username>'	=> "database username (default from config.xml)",
		'p <password>'	=> "database user password (default from config.xml)",
		'P <port>'	=> "database port number",
		'h'		=> "print this help screen",
		'G'		=> "Test data generator (create 3000 test tickets)",
		'A'		=> "Do a full agnostos installation",
	);
	# Print help
	print "Usage: $0 [options]\n";
	print "Available options:\n\n";
	my $maxlength = 0;
	foreach (keys %options) {
		if (length($_) > $maxlength) { $maxlength = length($_); }
	}
	
	foreach (sort {length($a) <=> length($b)} sort {uc($a) cmp uc($b)} keys %options) {
		printf "  -$_"." "x($maxlength-length($_)+2)."-- $options{$_}\n"
	}
	print "\nFor a complete guide on various options - read the agnostos manual\n";
	# Finally exit
	exit;
}

# Print help if requested
if (defined($option{h})) {
	PrintHelp;
}

# Silent execution?
if (!defined($option{s})) {
	$option{s} = 0;
} else {
	$option{s} = 1;
}


# Replacement of print function
sub mprint {
	my $what = shift || return;
	print $what if !$option{s};
}


# Check for incompatible options
if (defined($option{b}) && defined($option{r})) {
	print "Error: -r and -b can't be used together\n\n";
	PrintHelp;
}


# Get unix timestamp
my $timestamp = strftime('%s', localtime);


# Get list of existing backups
my @backups = glob("$backupdir/*");
$_ =~ s/^(.*)\/(.*?)$/$2/ foreach @backups;


# Get youngest backup
my $youngest_backup = 0;
foreach (@backups) {
	$youngest_backup = $_ if $_ > $youngest_backup;
}


# Get oldest backup
my $oldest_backup = $youngest_backup;
foreach (@backups) {
	$oldest_backup = $_ if $_ < $oldest_backup;
}




# Table/Fields hash
my %tables = (
	assigned	=> { 
				order		=> ['id', 'todoid', 'groupid', 'userid', 'depid'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							todoid		=> 'int(11) default NULL',
							groupid		=> 'int(11) default NULL',
							userid		=> 'int(11) default NULL',
							depid		=> 'int(11) default NULL',
						   },
				pk		=> 'id',
			   },
	audit		=> {
				order		=> ['id', 'todoid', 'comment', 'date'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							todoid		=> 'int(11) NOT NULL default \'0\'',
							comment		=> 'text',
							date		=> 'datetime default NULL',
						   },
				pk		=> 'id',
				key		=> 'todoid',
			   },
	department	=> {
				order		=> ['id', 'depname', 'status'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							depname		=> 'varchar(255) default NULL',
							status		=> 'enum(\'active\', \'inactive\') NOT NULL default \'active\'',
						   },
				pk		=> 'id',
			   },
	depmem		=> {
				order		=> ['id', 'depid', 'userid', 'groupid'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							depid		=> 'int(11) default NULL',
							userid		=> 'int(11) default NULL',
							groupid		=> 'int(11) default NULL',
						   },
				pk		=> 'id',
			   },
	files		=> {
				order		=> ['id', 'filename', 'size', 'todoid', 'data', 'date'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							filename	=> 'varchar(255) NOT NULL',
							size		=> 'bigint(20) NOT NULL',
							todoid		=> 'bigint(20) NOT NULL',
							data		=> 'text NOT NULL',
							date		=> 'datetime NOT NULL',
						   },
				pk		=> 'id',
			   },
	groupmem	=> {
				order		=> ['id', 'userid'],
				fields		=> {
							id		=> 'int(11) default NULL',
							userid		=> 'int(11) default NULL',
						   },
			   },
	logs		=> {
				order		=> ['id', 'user_id', 'date', 'action', 'target'],
				fields		=> {
							id		=> 'bigint(20) NOT NULL auto_increment',
							user_id		=> 'bigint(20) NOT NULL default \'0\'',
							date		=> 'datetime NOT NULL default \'0000-00-00 00:00:00\'',
							action		=> 'varchar(255) NOT NULL default \'\'',
							target		=> 'varchar(255) NOT NULL default \'\'',
						   },
				pk		=> 'id',
			   },
	session		=> {
				order		=> ['id', 'sid', 'since', 'expires'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							sid		=> 'varchar(32) NOT NULL default \'\'',
							since		=> 'bigint(20) NOT NULL default \'0\'',
							expires		=> 'bigint(20) NOT NULL default \'0\'',
						   },
				pk		=> 'id',
			   },
	session_data	=> {
				order		=> ['id', 'session_id', 'var', 'value'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							session_id	=> 'int(11) NOT NULL default \'0\'',
							var		=> 'varchar(255) default \'\'',
							value		=> 'varchar(255) default NULL',
						   },
				pk		=> 'id',
			   },
	settings	=> {
				order		=> ['id', 'userid', 'key', 'value'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							userid		=> 'int(11) NOT NULL default \'0\'',
							key		=> 'varchar(255) default NULL',
							value		=> 'varchar(255) default NULL',
						   },
				pk		=> 'id',
			   },
	todo		=> {
				order		=> ['id', 'parent_id', 'title', 'description', 'status', 'priority', 'note', 'date', 'completed_date'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							parent_id	=> 'int(11) DEFAULT 0',
							title		=> 'varchar(255) default NULL',
							description	=> 'text',
							status		=> 'enum(\'cancelled\', \'done\', \'in-progress\', \'queued\', \'wait\') default NULL',
							priority	=> 'int(11) default NULL',
							note		=> 'text',
							date		=> 'date default NULL',
							completed_date	=> 'datetime default NULL',
						   },
				pk		=> 'id',
			   },
	user		=> {
				order		=> ['id', 'username', 'email', 'authname', 'passwd', 'type', 'status'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							username	=> 'varchar(255) default NULL',
							email		=> 'varchar(255) default NULL',
							authname	=> 'varchar(16) default NULL',
							passwd		=> 'varchar(255) default NULL',
							type		=> 'varchar(10) NOT NULL default \'User\'',
							status		=> 'enum(\'active\', \'inactive\') NOT NULL default \'active\'',
						   },
				pk		=> 'id',
			   },
	workgroup	=> {
				order		=> ['id', 'groupname', 'depid', 'email', 'status'],
				fields		=> {
							id		=> 'int(11) NOT NULL auto_increment',
							groupname	=> 'varchar(255) default NULL',
							depid		=> 'bigint(20) NOT NULL',
							email		=> 'text',
							status		=> 'enum(\'active\', \'inactive\') NOT NULL default \'active\'',
						   },
				pk		=> 'id',
			   },
);



# Create database structure
sub db_create {
	mprint "Creating database structure\n\n";
	foreach my $table (keys %tables) {
		mprint("Table: $table\n");
		$object{mysql}->do("DROP TABLE IF EXISTS `$table`;");
		my $SQL = "CREATE TABLE `$table` (\n";
		my $index = 0;
		my @fieldsorder = @{$tables{$table}{order}};
		foreach my $field (@fieldsorder) {
			if ($index == $#fieldsorder) {
				if (defined($tables{$table}{pk})) {
					$SQL .= "  `$field` $tables{$table}{fields}{$field},\n";
				} else {
					$SQL .= "  `$field` $tables{$table}{fields}{$field}\n";
				}
			} else {
					$SQL .= "  `$field` $tables{$table}{fields}{$field},\n";
			}
			$index++;
		}
		if (defined($tables{$table}{pk})) {
			if (defined($tables{$table}{key})) {
				$SQL .= "  PRIMARY KEY (`$tables{$table}{pk}`),\n";
				$SQL .= "  KEY `$tables{$table}{key}` (`$tables{$table}{key}`)\n";
			} else {
				$SQL .= "  PRIMARY KEY (`$tables{$table}{pk}`)\n";
			}
		}

		$SQL .= ") ENGINE=MyISAM DEFAULT CHARSET=latin1;";
		$object{mysql}->do($SQL);
	}
}


# Do initial inserts in database
sub db_initial_inserts {
	mprint "Initial inserts\n";
	$object{mysql}->do("INSERT INTO `user` VALUES (2,'Root User','agnostos\@localhost','agnostos','agnostos','Admin','active');");
}


# Do a fresh db install (same as -c -i)
sub db_install {
	db_create;
	db_initial_inserts;
}


# Do a database backup
sub db_backup {
	mprint "Backing up database, copy: $timestamp\n";
	my $newbackupdir = "$backupdir/$timestamp";
	if (! -d $newbackupdir) {
		mkdir $newbackupdir || die "Unable to make new backup directory: $newbackupdir";
	}
	# Create table directory structure
	foreach my $table (keys %tables) {
		mprint "Table: $table\n";
		my $tablebdir = "$newbackupdir/$table";
		mkdir $tablebdir || die "Unable to make backup table directory: $tablebdir";
		# Primary key is id, now select data and create directories and store in files
		$object{mysql}->select("SELECT * FROM $table");
		while (my $row = $object{mysql}->fetchrow_hashref) {
			# Create id directory
			mkdir "$tablebdir/$$row{id}";
			foreach my $field (keys %{$tables{$table}{fields}}) {
				# Skip ID filed, directory name is the id
				if ($field eq 'id') { next; }
				
				# Create file and fill with data
				my $fname = "$tablebdir/$$row{id}/$field";
				open FH, ">$fname" || die "Can't create file: $fname";
				my $data = $$row{$field};
				if (!defined($data)) { $data = ''; }
				print FH $data;
				close FH;
			}
		}
	}

	# Assigned table backup
	
}



# Do a database restore
sub db_restore {
	my $timestamp = shift || return;
	mprint "Restoring database copy: $timestamp\n";
	my $newrestoredir = "$backupdir/$timestamp";
	if (! -d $newrestoredir) {
		die "Error: Selected database copy does not exist: $timestamp";
	}
	foreach my $table (keys %tables) {
		mprint "Table: $table\n";
		# First delete table if exists
		if (defined($option{t})) {
			# Truncate table
			$object{mysql}->do("TRUNCATE TABLE `$table`;");
		}

		my $tabledir = "$newrestoredir/$table";
		my @ids = glob("$tabledir/*");
		$_ =~ s/^(.*)\/(.*?)$/$2/ foreach (@ids);
		foreach my $id (@ids) {
			# Cycle through ids
			my %row = ();
			$/ = undef;
			my @order = @{$tables{$table}{order}};
			
			foreach my $field (@order) {
				if ($field eq 'id') { next; }
				# Read field file
				my $undef = 0;
				open (FH, "$tabledir/$id/$field") or $undef = 1;
				if ($undef) {
					$row{$field} = "NULL";
				} else {
					$row{$field} = <FH>;
					close FH;
				}
			}
			$row{id} = $id;
			
			# Prepare SQL statement
			my $SQL = "INSERT INTO `$table` (`".join('`, `', @order)."`) VALUES (";
			my $index = 0;
			foreach (@order) {
				if ($index == $#order) {
					$SQL .= "'".quotemeta($row{$_})."'";
				} else {
					$SQL .= "'".quotemeta($row{$_})."', ";
				}
				$index++;
			}
			$SQL .= ");";
			$object{mysql}->do($SQL);
		}
	}
}



# Ask for user input
sub input {
	my $text = shift || '';
	if ($text ne '') {
		print $text;
	}
	chomp(my $result = <>);
	return $result;
}


# Generate test data
sub db_testdatagenerator {
	# ask user for confirmation
	print "!!!!!!   WARNING   !!!!!!   WARNING   !!!!!!   WARNING   !!!!!!\n";
	print "TEST DATA GENERATOR *WILL* DESTROY ALL EXISTING DATA IN AGNOSTOS!\n";
	print "You need to confirm you want to proceed by typing 'yes' (anything else will abort)\n\n";
	my $OK = input "Are you sure you want to proceed? (Yes/No) [No] ";
	if (lc $OK ne 'yes') {
		print "Abort.\n\n";
		return;
	}
	print "\nTest data generator will now continue. Database backup will be created before existing data is deleted.\n";
	print "Press <RETURN> to continue...";
	db_backup;
	mprint "Deleting existing data...\n";
	# Use db_create do delete existing data
	db_create;
	# Do initial inserts
	db_initial_inserts;
	# Ask user for email addresses
	my @email;
	foreach (qw(user1 user2 admin_user1 admin_user2 workgroup_1 workgroup_2)) {
		my $done = 0;
		my $_email;
		while (!$done) {
			$_email = input "Please enter email addres for $_: ";
			# Check if email address is valid
			if ($_email =~ /^[\w\.\-]+\@[\w\.\-]+\.[a-z][a-z]+$/i) {
				$done = 1;
			} else {
				print "Invalid email address!\n";
			}
		}
		# correct email address specified
	}
	# create 10 departments
	
	# create 100 workgroups
	# create 3000 tasks
}




# Recursively delete filesystem directory tree
sub del_tree {
	my $dir = shift || return;

	$dir =~ s/^(.*)\/$/$1/;
	# Find hidden files/directories
	my @all = glob("$dir/.*");
	push(@all, $_) foreach glob("$dir/*");
	$_ =~ s/^(.*)\/(.*?)$/$2/ foreach @all;
	foreach my $item (@all) {
		if ($item eq '.' || $item eq '..') { next; }
		my $fullname = "$dir/$item";
		if (-f $fullname) { unlink $fullname; }
		if (-d $fullname) {
			del_tree("$fullname");
			if (!rmdir($fullname)) {
				print "Error removing directory ($fullname): $!\n";
			}
		}
	}
}


# Delete a database backup copy
sub db_delete {
	my $timestamp = shift || return;
	mprint "Removing database copy: $timestamp\n";

	my $deletedir = "$backupdir/$timestamp";
	if (! -d $deletedir || ! -w $deletedir) {
		mprint "Unable to remove database copy";
		exit;
	}

	del_tree($deletedir);
	rmdir($deletedir);
}



# (Re)Generate the XML config file
sub GenerateXML {
	my $agn_dir = shift;
	my %settings;

        foreach (qw(DBHost DBPort DBName DBUser DBPass AppRootDir SyslogPath AppModuleDir AppTemplatesDir Theme
        SessionExpirationTime SessionsPerIP SqlTemplatesDir cMessageSuccess cMessageFailure cMessageWarn
        cVTWaitingL cVTWaitingH cVTProgressL cVTProgressH cVTQueuedL cVTQueuedH cVTDoneL cVTDoneH cVTCancelledL cVTCancelledH cVTExpiredL cVTExpiredH
	vtPageSize
        smtpHost smtpPort SenderEmail
        FQDN
        UserAdminRights VTODO)) {
                $settings{$_} = $object{config}->Get($_);
        }
	if (!defined($agn_dir)) {
		$agn_dir = $object{config}->Get('AppRootDir');
	}

	# Set DB connection options
	defined($option{D}) and $settings{DBName} = $option{D};
	defined($option{H}) and $settings{DBHost} = $option{H};
	defined($option{P}) and $settings{DBPort} = $option{P};
	defined($option{U}) and $settings{DBUser} = $option{U};
	defined($option{p}) and $settings{DBPass} = $option{p};

	# Store settings in config file
        my $xml = '';

        $xml .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
        $xml .= "<!--\n\n";
        $xml .= "core/config/config.xml\n";
        $xml .= "Copyright (C) 2006 Bozhin Zafirov <bozhin\@abv.bg>\n\n";

        $xml .= "This software comes with ABSOLUTELY NO WARRANTY. For details, see\n";
        $xml .= "the enclosed file COPYING for license information (GPL). If you\n";
        $xml .= "did not receive this file, see http://www.gnu.org/licenses/gpl.txt.\n";
        $xml .= "-->\n\n";
        $xml .= "<config>\n";

        $xml .= "\t<!-- Database settings -->\n";
        foreach (qw(DBHost DBPort DBName DBUser DBPass)) {
                $xml .= "\t<$_>$settings{$_}</$_>\n";
        }

        $xml .= "\n";
        $xml .= "\t<!-- Application directories -->\n";
	$xml .= "\t<AppRootDir>$agn_dir</AppRootDir>\n";
        foreach (qw(SyslogPath AppModuleDir AppTemplatesDir SqlTemplatesDir)) {
                $xml .= "\t<$_>$settings{$_}</$_>\n";
        }

        $xml .= "\n";
        $xml .= "\t<!-- HTML settings -->\n";
        foreach (qw(Theme cMessageSuccess cMessageFailure cMessageWarn
                cVTWaitingL cVTWaitingH cVTProgressL cVTProgressH cVTQueuedL cVTQueuedH cVTDoneL cVTDoneH cVTCancelledL cVTCancelledH cVTExpiredL cVTExpiredH)) {
                $xml .= "\t<$_>$settings{$_}</$_>\n";
        }

        $xml .= "\n";
        $xml .= "\t<!-- Session settings -->\n";
        foreach (qw(SessionExpirationTime SessionsPerIP)) {
                $xml .= "\t<$_>$settings{$_}</$_>\n";
        }

        $xml .= "\n";
        $xml .= "\t<!-- SMTP settings -->\n";
        foreach (qw(smtpHost smtpPort SenderEmail)) {
                $xml .= "\t<$_>$settings{$_}</$_>\n";
        }

        $xml .= "\n";
        $xml .= "\t<!-- Domain settings -->\n";
        foreach (qw(FQDN)) {
                $xml .= "\t<$_>$settings{$_}</$_>\n";
        }


        $xml .= "\n";
        $xml .= "\t<!-- Other settings -->\n";
        foreach (qw(UserAdminRights VTODO)) {
                $xml .= "\t<$_>$settings{$_}</$_>\n";
        }

        $xml .= "</config>\n";

        # Write new configuration
        open (FH, '>', '../core/config/config.xml') || die "Unable to open config file (check for directory existence/file and user permissions";
        print FH $xml || die "Unable to store settings";
        close FH;
}




# Do a full interactive agnostos installation (without apache settings)
sub agnostos_install {
	print "Agnostos interactive installation process\n\n";
	# ask user for settings
	my $installdir = '';
	while ($installdir eq '') {
		$installdir = input "Please specify installation directory [/opt/agnostos/]: ";
		chomp($installdir);
		if ($installdir eq '') {
			# use default value
			$installdir = "/opt/agnostos/";
		}
		if (! -d $installdir) {
			# Try to make installation directory
			system "mkdir -p $installdir &> /dev/null";
			if (! -d $installdir) {
				print "Error: cannot use $installdir as agnostos root directory!\n";
				$installdir = '';
			}
		}
	}
	# Add trailing slash
	if ($installdir !~ /\/$/) {
		$installdir .= '/';
	}

	$option{D} = $option{D}||defined($object{config}->Get("DBName"))?$object{config}->Get("DBName"):'agnostos';
	$option{P} = $option{P}||defined($object{config}->Get("DBPort"))?$object{config}->Get("DBPort"):'';
	$option{H} = $option{H}||defined($object{config}->Get("DBHost"))?$object{config}->Get("DBHost"):'localhost';
	$option{p} = $option{p}||defined($object{config}->Get("DBPass"))?$object{config}->Get("DBPass"):'agn0st0s';
	$option{U} = $option{U}||$object{config}->Get("DBUser")||'agnostos';

	# Ask for database parameters
	my $dbhost = input "Enter MySQL DB host [$option{H}]: ";
	if ($dbhost eq '') {
		$dbhost = $option{H};
	}
	my $dbport = input "Enter MySQL DB port [$option{P}]: ";
	if ($dbport eq '') {
		$dbport = $option{P};
	}
	my $dbname = input "Enter MySQL DB name [$option{D}]: ";
	if ($dbname eq '') {
		$dbname = $option{D};
	}
	my $dbuser = input "Enter MySQL DB user [$option{U}]: ";
	if ($dbuser eq '') {
		$dbuser = $option{U};
	}
	my $dbpass = input "Enter MySQL DB password [$option{p}]: ";
	if ($dbpass eq '') {
		$dbpass = $option{p};
	}


	# old db variables
	my ($old_dbhost, $old_dbport, $old_dbname, $old_dbuser, $old_dbpass);
	my $previous_version = input "\n\nDo you have an old version of agnostos installed? (Yes/No) [No]: ";
	if (lc $previous_version eq 'y' || lc $previous_version eq 'ye' || lc $previous_version eq 'yes') {
		# ask for old database settings
		$old_dbhost = input "Enter MySQL DB host [$option{H}]: ";
		if ($old_dbhost eq '') {
			$old_dbhost = $option{H};
		}
		$old_dbport = input "Enter MySQL DB port [$option{P}]: ";
		if ($old_dbport eq '') {
			$old_dbport = $option{P};
		}
		$old_dbname = input "Enter MySQL DB name [$option{D}]: ";
		if ($old_dbname eq '') {
			$old_dbname = $option{D};
		}
		$old_dbuser = input "Enter MySQL DB user [$option{U}]: ";
		if ($old_dbuser eq '') {
			$old_dbuser = $option{U};
		}
		$old_dbpass = input "Enter MySQL DB password [$option{p}]: ";
		if ($old_dbpass eq '') {
			$old_dbpass = $option{p};
		}

	}

	# ask for apache user:group
	my $auser = input "Enter apache user [apache]: ";
	if ($auser eq '') {
		$auser = "apache";
	}
	my $agroup = input "Enter apache group [apache]: ";
	if ($agroup eq '') {
		$agroup = "apache";
	}

	# print summary
	print "\n\n";
	print "Installation directory: $installdir\n";
	print "MySQL DB host: $dbhost\n";
	print "MySQL DB port: $dbport\n";
	print "MySQL DB name: $dbname\n";
	print "MySQL DB user: $dbuser\n";
	print "MySQL DB pass: $dbpass\n";

	# print summary for old db settings
	if (lc $previous_version eq 'y' || lc $previous_version eq 'ye' || lc $previous_version eq 'yes') {
		print "Old Agnostos MySQL DB host: $old_dbhost\n";
		print "Old Agnostos MySQL DB port: $old_dbport\n";
		print "Old Agnostos MySQL DB name: $old_dbname\n";
		print "Old Agnostos MySQL DB user: $old_dbuser\n";
		print "Old Agnostos MySQL DB pass: $old_dbpass\n";
	}
	
	print "Apache owner : $auser:$agroup\n";
	
	# ask for confirmation
	my $OK = input "\n\nAre you sure you want to proceed? (Yes/No) [No] ";
	if (lc $OK ne 'yes') {
		print "Abort.\n\n";
		return;
	}
	print "\n\nInstalling agnostos...\n";
	# Store DB settings first
	print "Storing database settings...\n";
	GenerateXML($installdir);
	print "Copying files to installation directory...\n";
	system "cp -a ../* $installdir";
	print "Setting user:group...\n";
	system "chown $auser:$agroup $installdir -R";

	# backup old database if necessary
	if (lc $previous_version eq 'y' || lc $previous_version eq 'ye' || lc $previous_version eq 'yes') {
		print "Backing up old database structure\n";
		system ("$installdir/bin/old_backup ".
			(defined($old_dbhost)?"-h $old_dbhost ":"").
			(defined($old_dbport)?"-P $old_dbport ":"").
			(defined($old_dbname)?"-D $old_dbname ":"").
			(defined($old_dbuser)?"-U $old_dbuser ":"").
			(defined($old_dbpass)?"-p $old_dbpass ":""));
	}
	print "Creating database structure...\n";
	db_install;
	# restore old db data to new structure (if appropriate)
	if (lc $previous_version eq 'y' || lc $previous_version eq 'ye' || lc $previous_version eq 'yes') {
		print "Restoring old DB data...\n";
		system "$installdir/bin/agnctl -tR"
	}
	$installdir =~ s/\/$//;
	print "\n\nInstallation complete.\nIn order to finish your agnostos installation you need\nto add the following lines in your apache configuration: \n\n\n";
	print "Alias \"/agnostos\" \"$installdir/bin/cgi-bin\"\n";
	print "<Directory \"$installdir/bin/cgi-bin\">\n";
	print "		Options ExecCGI\n";
	print "		AllowOverride All\n";
	print "		AddHandler cgi-script .pl\n";
	print "		DirectoryIndex index.pl\n";
	print "</Directory>\n";

}





######################################################################################
# Cycle through commandline options
if (defined($option{A}) || defined($option{D}) || defined($option{P}) || defined($option{U})) {
	# Do a database reconnect (with options specified)
	$object{mysql}->disconnect;
	
	my $dbname = $option{D}||$object{config}->Get("DBName")||undef;
	my $dbport = $option{P}||$object{config}->Get("DBPort")||undef;
	my $dbhost = $option{H}||$object{config}->Get("DBHost")||undef;
	my $dbpass = $option{p}||$object{config}->Get("DBPass")||undef;
	my $dbuser = $option{U}||$object{config}->Get("DBUser")||undef;

	$object{config}->Set('DBUser', $dbuser);
	$object{config}->Set('DBPass', $dbpass);
	
	my $dsn = "dbi:mysql:database=$dbname".
		($dbhost?";host=$dbhost":"").
		($dbport?";port=$dbport":"");
	$object{mysql}->{dsn} = $dsn;
	# Connect to database
	$object{mysql}->connect;	
}


if (defined($option{I})) {
	if (!defined($option{D})) {
		$option{D} = "mysql";
	}
}


# Check if user is going to insert/update data in mysql database
if (defined($option{D}) && $option{D} eq "mysql" && (defined($option{c}) || defined($option{i}) || defined($option{I}) || defined($option{t}) || defined($option{b}) || defined($option{r}) || defined($option{R}))) {
	print "Manipulations in mysql database forbidden!\n";
	exit;
}



# Store settings in config file
if (defined($option{S})) {
	# Check for race conditions
	# FIXME
	GenerateXML;
	exit;
}


if (defined($option{b}) || defined($option{r}) || defined($option{R}) || defined($option{d})) {
	if (defined($option{b})) {
		# Do a database backup
		db_backup;
	} elsif ($option{r}) {
		# Do a database restore
		db_restore($option{r});
	} elsif ($option{R}) {
		# Do a database last backup restore
		db_restore($youngest_backup);
	} elsif ($option{d}) {
		# Delete backup copy
		db_delete($option{d});
	}
	# No more operations at a time
	exit;
}


if (defined($option{L}) || defined($option{l}) || defined($option{O})) {
	if ($option{L}) {
		# List last available
		mprint "Last available DB backup copy:\n";
		print "$youngest_backup\n";
	}
	if ($option{l}) {
		# List databases
		mprint "List of available DB copies:\n\n";
		print "  $_\n" foreach @backups;
	}
	if ($option{O}) {
		# List oldest database backup
		mprint "Oldest available backup:\n";
		print "$oldest_backup\n";
	}
	exit;
}

if (defined($option{c})) {
	# Create database
	db_create;
}
if (defined($option{i})) {
	# Initial DB inserts
	db_initial_inserts;
}

if (defined($option{I})) {
	# Do a fresh DB install
	db_install;
}
if (defined($option{G})) {
	# Do a test data generation
	db_testdatagenerator;
}
if (defined($option{A})) {
	# Do full interactive agnostos install
	agnostos_install;
}
