#!/usr/bin/perl -w

use File::Copy; 

my %params;
my %psa_params;
my @imp_params = qw( vhost_path domain_name install_prefix ssl_target_directory dbname dbuser dbpasswd admin_passwd admin_email website_name website_desc );
my $is_error=0;

sub check_parameter
{
    my ($param) = @_;
    unless (defined $params{$param}){
        return 0;
    } else {
        return 1;
    }
}
sub modify_file
{
    my ($fname, $fparams) = @_;

    unless (open F, $fname){
        print STDERR "postinstall: can't open file `$fname` for reading\n";
        return 0;
    }

    my $file_content;
    while (<F>){
        $file_content .= $_;
    }
    close F;
    my ($k,$v);
    while (($k,$v)=each(%$fparams)){
        $file_content =~ s/\@\@${k}\@\@/$v/g;
    }

    unless (open F, ">$fname"){
        print STDERR "postinstall: can't open file `$fname` for writing\n";
        return 0;
    }
    print F $file_content;
    close F;
    return 1;
}
sub mysql_quote
{
    my ($qstr) = @_;
    # replace ' for \'
    # replace \ for \\
    $qstr =~ s/\\/\\\\/g;
    $qstr =~ s/'/\\'/g;
    return $qstr;
}
sub php_quote
{
    my ($qstr) = @_;
    # replace ' for \'
    # replace \ for \\
    $qstr =~ s/\\/\\\\/g;
    $qstr =~ s/'/\\'/g;
    return $qstr;
}
sub shell_quote
{
    my ($qstr) = @_;
    # replace ' for \'
    # replace \ for \\
    $qstr =~ s/\\/\\\\/g;
    $qstr =~ s/"/\\\"/g;
    $qstr =~ s/\$/\\\$/g;
    return $qstr;
}
# parse input to hash
while (<STDIN>){
    my ($k,$v);
    if (/^([^=]+)=(.+)$/){
        $v = $2;
        chomp $v;
        $k = $1;
        $params{"$k"} = $v;
        print STDERR $_;
    }
}
# parse plesk config file

open PSACONF, '/etc/psa/psa.conf';
print "opening psa config\n";
while (<PSACONF>){
    chomp;
    unless (/^#/){
        if (/^(\s*[_a-zA-Z]+)\s+(.+?)\s*$/){
            # print "$1 : $2\n";
            $psa_params{$1} = $2;
        }
    }
}
close PSACONF;


# check important parameters
foreach (@imp_params){
    unless (check_parameter($_)){
        print "postinstall: no parameter $_ specified for application\n";
        $is_error = 1;
    }
}
if ($is_error){
    exit 1;
}

my $proto;
my $documents_directory;
if ($params{'ssl_target_directory'} eq 'true'){
    $documents_directory = 'httpsdocs';
    $proto = "https://";
} else {
    $documents_directory = 'httpdocs';
    $proto = "http://";    
}

#################################
#       Remote Databese Section # 
################################# 


my ($dbhost, $dbport, $dbremote_params, $dbstring);  
$dbremote_params = '';  
$dbstring = '';  
if (defined $params{'dbhost'} && $params{'dbhost'} ne '') {  
    my ($m_dbhost, $m_dbport);  
    $dbhost = $params{'dbhost'};  
    $m_dbhost = shell_quote($dbhost);  
    $dbremote_params .= " --host=\"${m_dbhost}\" ";  
} else {  
    my ($m_dbhost, $m_dbport);  
    $dbhost = 'localhost';  
    $m_dbhost = shell_quote($dbhost);  
    $dbremote_params .= " --host=\"${m_dbhost}\" ";  
}  
$dbstring .= $dbhost; 
if (defined $params{'dbport'} && $params{'dbport'} ne '') {  
    $dbport = $params{'dbport'};  
    $m_dbport = shell_quote($dbport);  
    $dbremote_params .= " --port=\"${m_dbport}\" ";  
    $dbstring .= ":$dbport"; 
} else { 
    $dbport = '';  
    $m_dbport = shell_quote($dbport);  
} 

################################# 
#       Path to root directory  # 
################################# 

my $root_dir; 
                         
if(0){ 
    $root_dir = $params{'vhost_path'}.'/'.'cgi-bin'.'/'.$params{'install_prefix'};
} 
else{ 
    $root_dir = $params{'vhost_path'}.'/'.$documents_directory.'/'.$params{'install_prefix'};
} 


################################################# 
#       Modification of configuration files     # 
################################################# 

my @config_files = ( "web/config.php" ); 
my %config_params = ( 
    "PROTO" => php_quote($proto),
    "DB_HOST" => php_quote($dbhost), 
    "DB_PORT" => php_quote($dbport), 
    "DB_STRING" => php_quote($dbstring),
    "DOMAIN_NAME" => php_quote($params{'domain_name'}), 
    "INSTALL_PREFIX" => php_quote($params{'install_prefix'}), 
    "ROOT_DIR" => php_quote($root_dir), 
    "SSL_MODE" => php_quote($params{'ssl_target_directory'}),     
    
	"DB_NAME" => php_quote($params{'dbname'}),
	"DB_USER" => php_quote($params{'dbuser'}),
	"DB_PASS" => php_quote($params{'dbpasswd'}),
	"ADMIN_PASS" => php_quote($params{'admin_passwd'}),
	"ADMIN_EMAIL" => php_quote($params{'admin_email'}),
	"WEBSITE_NAME" => php_quote($params{'website_name'}),
	"WEBSITE_DESC" => php_quote($params{'website_desc'})
 );
 
foreach my $config_file (@config_files) { 
    my $config_file_full = "${root_dir}/${config_file}"; 
    my $config_file_full_dist = $config_file_full;
    $config_file_full_dist =~ s/.php/.dist.php/; 
    $config_file_full_dist =~ s/.html/.dist.html/;     
    $config_file_full_dist =~ s/.ini/.dist.ini/;
    $config_file_full_dist =~ s/.inc/.dist.inc/; 
    $config_file_full_dist =~ s/.pl/.dist.pl/; 
    $config_file_full_dist =~ s/.dist.inc./.inc./; 
    $config_file_full_dist =~ s/.dist.ini./.ini./;             
           
    copy($config_file_full_dist, $config_file_full);
    unless (modify_file($config_file_full, \%config_params)){
        print STDERR "couldn't change file ${config_file_full}\n";
        exit 1;
    } 
} 
					 
                         
######################################################################### 
#       Modification of schema files and database initialisation        # 
######################################################################### 
                                         
my @schema_files = ( "reconfigure.sql" ); 
my %sql_params = ( 
    "PROTO" => mysql_quote($proto), 
    "DB_HOST" => mysql_quote($dbhost), 
    "DB_PORT" => mysql_quote($dbport), 
    "DB_STRING" => mysql_quote($dbstring),         
    "DOMAIN_NAME" => mysql_quote($params{'domain_name'}), 
    "INSTALL_PREFIX" => mysql_quote($params{'install_prefix'}), 
    "ROOT_DIR" => mysql_quote($root_dir), 
    "SSL_MODE" => mysql_quote($params{'ssl_target_directory'}),    
    
	"DB_NAME" => mysql_quote($params{'dbname'}),
	"DB_USER" => mysql_quote($params{'dbuser'}),
	"DB_PASS" => mysql_quote($params{'dbpasswd'}),
	"ADMIN_PASS" => mysql_quote($params{'admin_passwd'}),
	"ADMIN_EMAIL" => mysql_quote($params{'admin_email'}),
	"WEBSITE_NAME" => mysql_quote($params{'website_name'}),
	"WEBSITE_DESC" => mysql_quote($params{'website_desc'})
 );
 
my $mysql_bin = $psa_params{'MYSQL_BIN_D'}.'/mysql';
my $m_dbuser = shell_quote($params{'dbuser'});
my $m_dbpass = shell_quote($params{'dbpasswd'});
my $m_dbname = shell_quote($params{'dbname'});

foreach my $sql_file (@schema_files) { 
    my $sql_file_full = "${root_dir}/${sql_file}"; 
    my $sql_file_full_temp = "${root_dir}/${sql_file}".".sql";
    copy($sql_file_full, $sql_file_full_temp);
    unless (modify_file($sql_file_full_temp, \%sql_params)){
        print STDERR "couldn't change file ${sql_file_full_temp}\n";
        exit 1;
    }
    my $mysql_cmd = "${mysql_bin} -u\"${m_dbuser}\" -p\"${m_dbpass}\" \"${m_dbname}\" <${sql_file_full_temp}";
    $str_res = `$mysql_cmd`;
    if ($?){
        # error occured during mysql
        print STDERR "unable to import sql data:\n${str_res}\n";
        print STDERR "$mysql_cmd\n";
	unlink($sql_file_full_temp); 
        exit 1;
    }
    unlink($sql_file_full_temp);     
} 

exit 0;
