#!/usr/bin/perl -w

use File::Copy; 

my @imp_params = qw( vhost_path domain_name install_prefix ssl_target_directory dbname dbuser dbpasswd admin_login admin_passwd admin_email language );
my $is_error=0;

my %params;
my %psa_params;

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;	
}


#########################
#	Quote Section	#
#########################

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

sub parse_input_to_hash
{
    while (<STDIN>){
	my ($k,$v);
	if (/^([^=]+)=(.+)$/){
		$v = $2;
		chomp $v;
		$k = $1;
		$params{"$k"} = $v;
		print STDERR $_;
	}
    }
}

parse_input_to_hash();

# parse plesk config file

sub 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;
}

parse_plesk_config_file();

# check parameters

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

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

check_parameters();

#########################
#	SSL Section	#
#########################

sub get_proto
{
    my $proto;
    if ($params{'ssl_target_directory'} eq 'true'){
            $proto = 'https://';
    } else {
            $proto = 'http://';
    }
    return $proto;
}

sub get_documents_directory
{
    my $documents_directory;
    if ($params{'ssl_target_directory'} eq 'true'){
            $documents_directory = 'httpsdocs';
    } else {
            $documents_directory = 'httpdocs';
    }
    return $documents_directory;
}

sub get_ssl_enabled
{
    my $ssl_enabled;
    if ($params{'ssl_target_directory'} eq 'true'){
            $ssl_enabled = 1;
    } else {
            $ssl_enabled = 0;
    }
    return $ssl_enabled;
}


my $proto = get_proto();
my $documents_directory = get_documents_directory();
my $ssl_enabled = get_ssl_enabled();

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

sub get_dbhost
{
    my $dbhost;
    if (defined $params{'dbhost'} && $params{'dbhost'} ne '') { 
        $dbhost = $params{'dbhost'}; 
    } else { 
        $dbhost = 'localhost'; 
    } 
}

sub get_dbport
{
    my $dbport;
    if (defined $params{'dbport'} && $params{'dbport'} ne '') { 
        $dbport = $params{'dbport'}; 
    } else {
        $dbport = '3306'; 
    }
    return $dbport;
}

sub get_dbremote_params
{
    my $dbremote_params = '';

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

sub get_dbstring
{
    my $dbstring = '';
    my $dbhost = '';
    my $dbport = '';
    

    if (defined $params{'dbhost'} && $params{'dbhost'} ne '') {
        $dbhost = $params{'dbhost'};
    } else {
        $dbhost = 'localhost';
    }
    $dbstring .= $dbhost;
    if (defined $params{'dbport'} && $params{'dbport'} ne '') {
        $dbport = $params{'dbport'};
        $dbstring .= ":$dbport";
    }
    return $dbstring;
}


my $dbhost = get_dbhost();
my $dbport = get_dbport();
my $dbremote_params = get_dbremote_params();
my $dbstring = get_dbstring();

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

sub get_root_dir
{
    my $root_dir = '';
    $root_dir = $params{'vhost_path'}.'/'.$documents_directory.'/'.$params{'install_prefix'};

    if($params{'install_prefix'} eq "."){
        $root_dir =~ s/\/\.//g;
    }
    return $root_dir;
}

sub get_root_url
{
    my $root_url = '';
    $root_url = $proto.$params{'domain_name'}."/".$params{'install_prefix'};
			
    if($params{'install_prefix'} eq "."){
        $root_url =~ s/\/\.//g; 
    }
    return $root_url;
}

sub get_root_dir_cgi
{
    my $root_dir_cgi = $params{'vhost_path'}.'/'.'cgi-bin'.'/'.$params{'install_prefix'};
    return $root_dir_cgi;
}

sub get_install_prefix
{
    my $install_prefix;
    if($params{'install_prefix'} eq "."){
        $install_prefix = "";
    }
    else{
        $install_prefix = $params{'install_prefix'};
    }
    return $install_prefix;
}


my $root_dir = get_root_dir();
my $root_url = get_root_url();
my $root_dir_cgi = get_root_dir_cgi();
my $install_prefix = get_install_prefix();

# If installation in docroot then chenge `install_prefix` from `.` to ``
$params{'install_prefix'} = $install_prefix;

if(0){
    $root_dir = $root_dir_cgi;
}

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

my @config_files = ( "config.inc.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),
    "ROOT_URL" => php_quote($root_url),    
    "SSL_ENABLED" => php_quote($ssl_enabled),
    "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_LOGIN" => php_quote($params{'admin_login'}),
	"ADMIN_PASS" => php_quote($params{'admin_passwd'}),
	"ADMIN_EMAIL" => php_quote($params{'admin_email'}),
	"UI_LANG" => php_quote($params{'language'})
 );

sub config_file_modification
{
    my $app_config_template = "app_config.template";
    if (-e "${root_dir}/${app_config_template}"){
        foreach my $config_file (@config_files) {
	    my $config_file_full = "${root_dir}/${config_file}";
	    my $config_template = "${root_dir}/${app_config_template}";
    	    unless (open F, $config_template){
		print "can't open file `$config_template` for reading\n";
    		return 0;
	    }
    	    my $conf_templ_str;
	    my $param_name;
    	    while (<F>){
		my $tt;
        	$conf_templ_str = $_;
	    	$conf_templ_str =~ s/\n//;
		($param_name) = split(/=/,$conf_templ_str);
		if($tt eq ''){
	    	    ($param_name) = split(/,/,$conf_templ_str);
                }
		($param_name) =~ s/\$/\\\$/g;
		($param_name) =~ s/\'/\\'/g;
		($param_name) =~ s/\"/\\"/g;
		($param_name) =~ s/\[/\\[/g;
		($param_name) =~ s/\]/\\]/g;
		($param_name) =~ s/\(/\\(/g;
		($param_name) =~ s/\)/\\)/g;

		my $file_content = '';
		my $cur_str = '';
                unless (open F2, $config_file_full){
        	    print "can't open file `$config_template` for reading\n";
        	    return 0;
		}
		
	        while (<F2>){
		    $cur_str = $_;
		    if($tt eq ''){
	                $cur_str =~ s/${param_name},[^\n]*/${conf_templ_str}/;
	            }
	            else{
	                $cur_str =~ s/${param_name}=[^\n]*/${conf_templ_str}/;
	            }
        	    $file_content .= $cur_str;
		}
		close F2;
		unless (open F3, ">$config_file_full"){
        	    print "can't open file `$config_file_full` for writing\n";
        	    return 0;
    		}
    		print F3 $file_content;
		close F3;
	    }
            unless (modify_file($config_file_full, \%config_params)){
                print STDERR "couldn't change file ${config_file_full}\n";
                exit 1;
            }
        }
        close F;
    }
    else{
        foreach my $config_file (@config_files) {
            my $config_file_full = "${root_dir}/${config_file}";
            my $config_file_full_dist = ${config_file};
	    $config_file_full_dist =~ s/\.php/\.php\.in/;
	    unless(-e "${root_dir}/${config_file_full_dist}"){
        	$config_file_full_dist = $config_file;
        	$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("${root_dir}/$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;
            }
        }
    }
}

config_file_modification();
 
######################################################################### 
#       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),
    "ROOT_URL" => mysql_quote($root_url),
    "SSL_ENABLED" => mysql_quote($ssl_enabled),
    "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_LOGIN" => mysql_quote($params{'admin_login'}),
	"ADMIN_PASS" => mysql_quote($params{'admin_passwd'}),
	"ADMIN_EMAIL" => mysql_quote($params{'admin_email'}),
	"UI_LANG" => mysql_quote($params{'language'})
 );
 
sub schema_file_modification
{
    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} ${dbremote_params} -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";
	    exit 1;
        }
	unlink($sql_file_full_temp);
    }
}

schema_file_modification();

exit 0;
