#!/usr/bin/perl

# ispCP ω (OMEGA) a Virtual Hosting Control Panel
# Copyright (C) 2001-2006 by moleSoftware GmbH - http://www.molesoftware.com
# Copyright (C) 2006-2010 by isp Control Panel - http://ispcp.net
#
# Version: $Id: ispcp-setup 3631 2010-11-16 13:43:11Z benedikt $
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is "VHCS - Virtual Hosting Control System".
#
# The Initial Developer of the Original Code is moleSoftware GmbH.
# Portions created by Initial Developer are Copyright (C) 2001-2006
# by moleSoftware GmbH. All Rights Reserved.
# Portions created by the ispCP Team are Copyright (C) 2006-2010 by
# isp Control Panel. All Rights Reserved.
#
# The ispCP ω Home Page is:
#
#    http://isp-control.net
#

# Note to dev:
#
# It's important for the recovery process that all the subroutines defined here
# are idempotent. That wants mean that if a subroutine is called again and
# again, the final result should be the same. For example, if an error occurs
# and the script ends, and then the script is run again, the final result
# should be identical as if the script was run once.

use strict;
use warnings;
no warnings 'once';
use feature 'state';
use FindBin;
use lib "$FindBin::Bin/..";
use PerlVendor::Capture::Tiny qw/capture_merged/;

require 'ispcp_common_code.pl';
require 'ispcp-setup-methods.pl';

# We use our own system() subroutine implementation
# See in the ispcp-setup-methods.pl file
use subs 'system';

################################################################################
#                            Built-in subroutines overriding                   #
################################################################################

################################################################################
# Execute a system command. This is an overridden for the system() function
#
# This subroutine overwrites the built-in function that allows to perform some
# logging operation for the external commands output.
#
# See http://perldoc.perl.org/functions/system.html
#
sub system {
	my @args = @_;

	state $regExp = qr /(clear|preinst|postinst|tput)/o;

	if($_[0] !~ $regExp) {
		my $output = capture_merged { CORE::system(@args); };
		chomp($output);
		push_el(\@main::el, 'system()', "[DEBUG] $output") if $output ne '';
	} else {
		CORE::system(@args);
	}
}

################################################################################
#                                 Subroutines                                  #
################################################################################

################################################################################
# Display a welcome note
#
# @return void
#
sub welcome_note {

	push_el(\@main::el, 'welcome_note()', 'Starting...');

	print colored(
		['bold underline'],
		"\n\tWelcome to ispCP '$main::cfg{'Version'}' Setup Dialog.\n\n"
	), "\tThis program will set up ispCP OMEGA system on your server.\n";

	push_el(\@main::el, 'welcome_note()', 'Ending...');
}

################################################################################
# Process user dialog
#
# In order:
#  Host Questions, SQL Questions, ispCP ftp SQL user questions,
#  PMA control user questions, Admin questions, Configuration questions,
#  FastCGI-Version questions, PHP Timzeone question, Awstats question,
#  Awstats mode question
#
# @return void
#
sub user_dialog {

	push_el(\@main::el, 'user_dialog()', 'Starting...');

	print "\n\tNext you are asked to enter a \"fully qualified hostname\" " .
		"(FQHN).\n\tFor more infos read http://en.wikipedia.org/wiki/FQDN.\n\n";

	# Note to dev:
	# CODE: run once
	# REF: run in loop
	for(
		\&ask_hostname, \&ask_eth, \&ask_vhost, \&ask_db_host, \\&ask_db_name,
		\\&ask_db_user, \&ask_db_password, \&ask_db_ftp_user, \&ask_db_ftp_password,
		\&ask_db_pma_user, \&ask_db_pma_password, \\&ask_admin, \&ask_admin_password,
		\&ask_admin_email, \&ask_second_dns, \&ask_resolver, \&ask_mysql_prefix,
		\&ask_fastcgi, \&ask_timezone, \&ask_awstats_on
	) {
		my $rs;

		if(ref ne 'REF') {
			do {$rs = &{$_};} while ($rs);
		} else {
			&{$$_}
		}
	}

	if ($main::ua{'awstats_on'} eq 'yes' || $main::ua{'awstats_on'} eq 'y') {
		my $rs;

		do {
			$rs = ask_awstats_dyn();
		} while ($rs == 1);
	} else {
		# Dummy to prevent warnings
		$main::ua{'awstats_dyn'} = 0;
	}

	system('clear');
	spacer();

	print colored(
		['bold'], "\n\tThe program is now ready to set up ispCP on your system.\n"
	);

	# Last chance to stop the installation process
	do {
		print "\tDo you want to continue? [Y/n]: ";
		chomp($_ = <STDIN>);
	} while (!/^(y|yes|n|no|)$/i);

	my $rdata = "\L$1";

	# Exit with a notice if the user chooses to abort the setup process
	($rdata eq '' || $rdata eq 'y' ||$rdata eq 'yes') or exit_msg(
		0, colored(['bold blue'], "\n\t[NOTICE] ") .
		"The setup process was aborted by user...\n"
	);

	push_el(\@main::el, 'user_dialog()', 'Ending...');
}

################################################################################
# Perform some tests to ensure that all works correctly
#
# Note: For now, only a Mysql Server connection test is performed
#
# @return void
#
sub check_host_system {

	push_el(\@main::el, 'check_host_system()', 'Starting...');

	subtitle('Mysql server connection:');

	my $rs = check_sql_connection(
		$main::ua{'db_user'}, $main::ua{'db_password'}, '', $main::ua{'db_host'}
	);
	print_status($rs, 'exit_on_error');

	push_el(\@main::el, 'check_host_system()', 'Ending...');
}

################################################################################
# Create users and groups for different services
#
# @return int 0 on success, other on failure
#
sub setup_system_users {

	push_el(\@main::el, 'setup_system_users()', 'Starting...');

	my ($rs, $cmd);

	## Mailbox user
	my ($fuid, $fgid) = (
		$main::cfg{'MTA_MAILBOX_UID_NAME'}, $main::cfg{'MTA_MAILBOX_GID_NAME'}
	);
	my ($uid, $gid);

	my @udata = ();
	my @gdata = ();

	@gdata = getgrnam($fgid);

	if (scalar(@gdata) == 0) { # we have not this one group data;
		$rs = sys_command("$main::cfg{'CMD_GROUPADD'} $fgid");
		return $rs if ($rs != 0);

		@gdata = getgrnam($fgid);
	}

	$gid = $gdata[2];

	@udata = getpwnam($fuid);

	if (scalar(@udata) == 0) { # we have not this one user data;
		if ($main::cfg{'ROOT_GROUP'} eq 'wheel') {
			$cmd = "$main::cfg{'CMD_USERADD'} $fuid -c vmail-user -s /bin/false";
		} else {
			$cmd = "$main::cfg{'CMD_USERADD'} -c vmail-user -g $gid -s " .
			"/bin/false $fuid";
		}

		$rs = sys_command($cmd);
		return $rs if ($rs != 0);

		@udata = getpwnam($fuid);
	}

	$uid = $udata[2];
	$main::ua{'su_uid'} = $uid;
	$main::ua{'su_gid'} = $gid;

	## FCGI Master user
	my ($muid, $mgid, $prefix) = (
		$main::cfg{'APACHE_SUEXEC_MIN_UID'}, $main::cfg{'APACHE_SUEXEC_MIN_GID'},
		$main::cfg{'APACHE_SUEXEC_USER_PREF'}
	);

	my ($vuuid, $vugid);

	@gdata = getgrnam($prefix.$mgid);
	@udata = getpwnam($prefix.$muid);

	if (scalar(@gdata) == 0) { # we do not have this group
		if ($main::cfg{'ROOT_GROUP'} eq 'wheel') {
			$cmd = "$main::cfg{'CMD_GROUPADD'} $prefix$mgid -g $mgid";
		} else {
			$cmd = "$main::cfg{'CMD_GROUPADD'} -g $mgid $prefix$mgid";
		}

		$rs = sys_command($cmd);
		return $rs if ($rs != 0);
	}

	# create user and folder
	if (scalar(@udata) == 0) { # we do not have this user
		if ($main::cfg{'ROOT_GROUP'} eq 'wheel') {
			$cmd = "$main::cfg{'CMD_USERADD'} $prefix$muid $prefix$muid -d " .
				"$main::cfg{'PHP_STARTER_DIR'}/master -m -c vu-master -g " .
				"$prefix$mgid -s /bin/false -u $muid $prefix$muid";
		} else {
			$cmd = "$main::cfg{'CMD_USERADD'} -d  $main::cfg{'PHP_STARTER_DIR'}" .
			"/master -m -c vu-master -g $prefix$mgid -s /bin/false -u $muid " .
			"$prefix$muid";
		}

		$rs = sys_command($cmd);
		return $rs if ($rs != 0);
	} else {
		# change folder permissions and owner
		$rs = setfmode(
			"$main::cfg{'PHP_STARTER_DIR'}/master", "$prefix$muid",
			"$prefix$mgid", 0755
		);
		return $rs if ($rs != 0);
	}

	$main::ua{'vu_uid'} = $muid;
	$main::ua{'vu_gid'} = $mgid;

	push_el(\@main::el, 'setup_system_users()', 'Ending...');

	0;
}

################################################################################
# create all directories required by ispCP and the managed services
#
# @return int 0 on success, other on failure
#
sub setup_system_dirs {

	push_el(\@main::el, 'setup_system_dirs()', 'Starting...');

	for (
		[$main::cfg{'APACHE_WWW_DIR'}, $main::cfg{'APACHE_USER'},$main::cfg{'APACHE_GROUP'}],
		[$main::cfg{'APACHE_USERS_LOG_DIR'}, $main::cfg{'APACHE_USER'},$main::cfg{'APACHE_GROUP'}],
		[$main::cfg{'APACHE_BACKUP_LOG_DIR'}, $main::cfg{'ROOT_USER'},$main::cfg{'ROOT_GROUP'}],
		[$main::cfg{'MTA_VIRTUAL_CONF_DIR'}, $main::cfg{'ROOT_USER'},$main::cfg{'ROOT_GROUP'}],
		[$main::cfg{'MTA_VIRTUAL_MAIL_DIR'}, $main::cfg{'ROOT_USER'},$main::cfg{'ROOT_GROUP'}],
		[$main::cfg{'LOG_DIR'}, $main::cfg{'ROOT_USER'},$main::cfg{'ROOT_GROUP'}],
		[$main::cfg{'BACKUP_FILE_DIR'}, $main::cfg{'ROOT_USER'},$main::cfg{'ROOT_GROUP'}],
		[$main::cfg{'PHP_STARTER_DIR'},
		"$main::cfg{'APACHE_SUEXEC_USER_PREF'}$main::cfg{'APACHE_SUEXEC_MIN_UID'}",
		"$main::cfg{'APACHE_SUEXEC_USER_PREF'}$main::cfg{'APACHE_SUEXEC_MIN_GID'}"
		]
	) {
		my $rs = make_dir($_->[0], $_->[1], $_->[2], 0755);
		return $rs if ($rs != 0);
	}

	# AWStats dir, use of $main::ua{'awstats_on'}, instead of
	# $main::cfg{'AWSTATS_ACTIVE'}, because variable not yet set.
	if ($main::ua{'awstats_on'} eq 'yes' || $main::ua{'awstats_on'} eq 'y') {
		my $rs = make_dir(
			$main::cfg{'AWSTATS_CACHE_DIR'}, $main::cfg{'APACHE_USER'},
			$main::cfg{'APACHE_GROUP'}, 0755
		);
		return $rs if ($rs != 0);
	}

	push_el(\@main::el, 'setup_system_dirs()', 'Ending...');

	0;
}

################################################################################
# Update the ispcp.conf file with user data and reload all the configuration
#
# @return int 0 on success, other on failure
#
sub setup_config {

	push_el(\@main::el, 'setup_config()', 'Starting...');

	for(
		['SERVER_HOSTNAME', \$main::ua{'hostname'}],
		['BASE_SERVER_IP', \$main::ua{'eth_ip'}],
		['BASE_SERVER_VHOST', \$main::ua{'admin_vhost'}],
		['DATABASE_HOST', \$main::ua{'db_host'}],
		['DATABASE_NAME', \$main::ua{'db_name'}],
		['DATABASE_USER', \$main::ua{'db_user'}],
		['MTA_MAILBOX_MIN_UID', \$main::ua{'su_uid'}],
		['MTA_MAILBOX_UID', \$main::ua{'su_uid'}],
		['MTA_MAILBOX_GID', \$main::ua{'su_gid'}],
		['APACHE_SUEXEC_MIN_UID', \$main::ua{'vu_uid'}],
		['APACHE_SUEXEC_MIN_GID', \$main::ua{'vu_gid'}],
		['DEFAULT_ADMIN_ADDRESS', \$main::ua{'admin_email'}],
		['AWSTATS_ACTIVE', \$main::ua{'awstats_on'}],
		['AWSTATS_MODE', \$main::ua{'awstats_dyn'}],
		['PHP_FASTCGI', \$main::ua{'php_fastcgi'}],
		['PHP_TIMEZONE', \$main::ua{'php_timezone'}],
		['SECONDARY_DNS', \$main::ua{'secondary_dns'}],
		['LOCAL_DNS_RESOLVER', \$main::ua{'resolver'}],
		['MYSQL_PREFIX', \$main::ua{'mysql_prefix'}],
		['MYSQL_PREFIX_TYPE', \$main::ua{'mysql_prefix_type'}]
	) {
		my $rs = set_conf_val($_->[0], ${$_->[1]});
		return $rs if ($rs != 0);
	}

	# If not empty password, encrypt it before store it in ispcp.conf file
	if ($main::ua{'db_password'} ne '') {
		my ($rs, $rdata) = encrypt_db_password($main::ua{'db_password'});
		return $rs if ($rs != 0);

		$rs = set_conf_val('DATABASE_PASSWORD', $rdata);
		return $rs if ($rs != 0);
	}

	# Updating the main ispCP configuration file with news values and reloads
	# all configuration parameters from it. Also, resets the DSN.
	my $rs = store_conf();
	return $rs if ($rs != 0);

	push_el(\@main::el, 'setup_config()', 'Ending...');

	0;
}

################################################################################
# Creating ispCP database
#
# @return int 0 on success, other on failure
#
sub setup_ispcp_database {

	push_el(\@main::el, 'setup_ispcp_database()', 'Starting...');

	my $ispCPdbName = $main::ua{'db_name'};

	# Converting to ASCII (Punycode)
	my $dbHost = idn_to_ascii($main::db_host, 'utf-8');

	# Setting DSN (We should don't select database here)
	@main::db_connect = (
		"DBI:mysql::$dbHost", $main::db_user, $main::db_pwd
	);

	# Forcing reconnection
	$main::db = undef;

	my $sql = "SHOW DATABASES LIKE '$main::ua{'db_name'}';";

	# Check if the a database with same name already exist
	my ($rs, $rdata) = doSQL($sql);
	return $rs if($rs != 0);

	while(@$rdata[0]) {
		# Database with same name already exists
		print colored(['bold yellow'], "\n\n\t[WARNING] ") .
			"The '$main::ua{'db_name'}' database already exist!\n";

		# We must have user confirmation for database drop
		do {
			print "\n\tWould you really drop the current database? [Y/n] ";
			chomp($rdata = <STDIN>);

			if($rdata =~ /^(?:(y|yes|)|(n|no))$/i) {
				$rs = defined $1 ? 1 : 0;
			} else {
				print colored(['bold red'], "\n\t[ERROR] ") .
					"You entered an unrecognized value!\n";

				$rs = -1;
			}
		} while ($rs == -1);

		if(!$rs) {
			print colored(['bold blue'], "\n\t[NOTICE] ") .
				"Next, you'll be asked again a name for the ispCP database.\n" .
				"\tYou should choose a name that is not already used!\n";

			ask_db_name();

			# Check if the a database with same name already exist
			($rs, $rdata) = doSQL($sql);
			return $rs if($rs != 0);
		} else {
			push_el(
				\@main::el, 'setup_ispcp_database()',
				"Removing database $main::ua{'db_name'}"
			);

			($rs) = doSQL("DROP DATABASE `$main::ua{'db_name'}`;");
			return $rs if($rs != 0);
			last;
		}
	}

	# Updating the configuration file and redefinition of the DSN. We also
	# forcing the re-connection to MySQL server on the next query
	if($ispCPdbName ne $main::ua{'db_name'}) {
		$rs = set_conf_val('DATABASE_NAME', $main::ua{'db_name'});
		return $rs if($rs != 0);

		$rs = store_conf();
		return $rs if($rs != 0);
	} else {
		# Resetting the DSN to the default values and forcing the re-connection
		# to the database on the next query
		setup_main_vars();
	}

	## Creating the ispCP database

	($rs, $rdata) = get_file("$main::cfg{'CONF_DIR'}/database/database.sql");
	return $rs if ($rs != 0);

	# Setting the database name in the SQL schema template file
	$rdata =~ s/\{DATABASE_NAME\}/$main::db_name/gi;

	# Storing the final SQL file
	$rs = store_file(
		'/tmp/db.sql', $rdata, $main::cfg{'ROOT_USER'}, $main::cfg{'ROOT_GROUP'},
		0644
	);
	return $rs if ($rs != 0);

	# Escape " and ' characters
	$main::db_pwd =~ s/([\'\"])/\\$1/g;

	$rs = sys_command(
		"$main::cfg{'CMD_MYSQL'} --host='$dbHost' --user='$main::db_user' " .
		 "--pass='$main::db_pwd' < /tmp/db.sql"
	);
	return $rs if ($rs != 0);

	# Removing the temporary SQL schema file
	$rs = del_file('/tmp/db.sql');
	return $rs if ($rs != 0);

	push_el(\@main::el, 'setup_ispcp_database()', 'Ending...');
}

################################################################################
# Creating default language table
#
# @return int 0 on success, other on failure
#
sub setup_default_language_table {

	push_el(\@main::el, 'setup_default_language_table()', 'Starting...');

	# Converting to ASCII (Punycode)
	my $dbHost = idn_to_ascii($main::db_host, 'utf-8');

	my $rs = sys_command(
		"$main::cfg{'CMD_MYSQL'} --host='$dbHost' --user='$main::db_user' " .
		"--pass='$main::db_pwd' $main::db_name " .
		"< $main::cfg{'CONF_DIR'}/database/languages.sql"
	);
	return $rs if ($rs != 0);

	push_el(\@main::el, 'setup_default_language_table()', 'Ending...');
}

################################################################################
# Setup ispCP database default data
#
# Default data are:
#
# - Data for the first ispCP administrator
# - Data for the first Ip
# - Data for the proftpd SQL user
#
# @return int 0 on success, other on failure
#
sub setup_default_sql_data {

	push_el(\@main::el, 'setup_default_sql_data()', 'Starting...');

	## First ispCP administrator data - Begin

	my $admin_password = crypt_md5_data($main::ua{'admin_password'});

	push_el(
		\@main::el, 'setup_default_sql_data()',
		'[DEBUG] Inserting primary admin account data...'
	);

	my ($rs) = doSQL(
		"INSERT INTO `admin` (`admin_id`, `admin_name`, `admin_pass`, `admin_type`, " .
		"`email`) VALUES (1, '$main::ua{'admin'}','$admin_password', 'admin', " .
		"'$main::ua{'admin_email'}');"
	);
	return $rs if ($rs != 0);

	($rs) = doSQL('INSERT INTO `user_gui_props` (`user_id`) values (1);');
	return $rs if ($rs != 0);

	## First Ip data - Begin

	push_el(
		\@main::el, 'setup_default_sql_data()',
		'[DEBUG] Inserting primary Ip data...'
	);

	($rs) = doSQL(
		"INSERT INTO `server_ips` (`ip_id`, `ip_number`, `ip_domain`, `ip_alias`) " .
		"VALUES (1, '$main::ua{'eth_ip'}', '$main::ua{'hostname'}', " .
		"'$main::ua{'hostname'}');"
	);
	return $rs if ($rs != 0);

	## Proftpd SQL user data - Begin

	# Converting to ASCII (Punycode)
	my $dbHost = idn_to_ascii($main::db_host, 'utf-8');

	# First, we redefine the DNS to use mysql database
	@main::db_connect = (
		"DBI:mysql:mysql:$dbHost", $main::db_user, $main::db_pwd
	);

	# And then, we force reconnection to the database
	$main::db = undef;

	my $vftp_sql_user = $main::ua{'db_ftp_user'};
	my $vftp_sql_password = $main::ua{'db_ftp_password'};

	# Ensuring that the user doesn't already exist by trying to remove it from
	# both 'tables_priv' and 'user' tables

	($rs) = doSQL(
		"DELETE FROM `tables_priv` WHERE `Host` = '$dbHost' AND `Db` = " .
		"'$main::db_name' AND `User` = '$vftp_sql_user';"
	);
	return $rs if ($rs != 0);

	($rs) = doSQL(
		"DELETE FROM `user` WHERE `Host` = '$dbHost' AND `User` = '$vftp_sql_user';"
	);
	return $rs if ($rs != 0);

	push_el(
		\@main::el, 'setup_default_sql_data()',
		'[DEBUG] Reloading all SQL privileges...'
	);

	# Reloading the SQL privileges for all users
	($rs) = doSQL('FLUSH PRIVILEGES;');
	return $rs if ($rs != 0);

	push_el(
		\@main::el, 'setup_default_sql_data()',
		'[DEBUG] Inserting Proftpd SQL user account data...'
	);

	# The Proftpd SQL user should have some rights on the 'ftp_group' table
	($rs) = doSQL(
		"GRANT SELECT,INSERT,UPDATE,DELETE ON `$main::db_name`.`ftp_group` TO " .
	    "'$vftp_sql_user'\@'$dbHost' IDENTIFIED BY '$vftp_sql_password';"
	);
	return $rs if ($rs != 0);

	# The Proftpd SQL user should have some rights on the 'ftp_users' table
	($rs) = doSQL(
		"GRANT SELECT,INSERT,UPDATE,DELETE ON `$main::db_name`.`ftp_users` TO " .
		"'$vftp_sql_user'\@'$dbHost' IDENTIFIED BY '$vftp_sql_password';"
	);
	return $rs if ($rs != 0);

	# The Proftpd SQL user should have some rights on the 'quotalimits' table
	($rs) = doSQL(
		"GRANT SELECT,INSERT,UPDATE,DELETE ON `$main::db_name`.`quotalimits` TO " .
		"'$vftp_sql_user'\@'$dbHost' IDENTIFIED BY '$vftp_sql_password';"
	);
	return $rs if ($rs != 0);

	# The Proftpd SQL user should have some rights on the 'quotatallies' table
	($rs) = doSQL(
		"GRANT SELECT,INSERT,UPDATE,DELETE ON `$main::db_name`.`quotatallies` TO " .
		"'$vftp_sql_user'\@'$dbHost' IDENTIFIED BY '$vftp_sql_password';"
	);
	return $rs if ($rs != 0);

	push_el(\@main::el, 'setup_default_sql_data()', 'Ending...');
}

################################################################################
# Create the system 'hosts' file
#
# @return int 0 on success, other on failure
#
sub setup_hosts {

	push_el(\@main::el, 'setup_hosts()', 'Starting...');

	# Converting to ASCII (Punycode)
	my $hostname = idn_to_ascii($main::ua{'hostname'}, 'utf-8');
	my $host = idn_to_ascii($main::ua{'hostname_local'}, 'utf-8');
	my $hostname_local = "$hostname.local";
	my $ip = $main::ua{'eth_ip'};

	if(!-e '/etc/hosts.bkp') {
		my $rs = sys_command_rs(
			"$main::cfg{'CMD_CP'} -fp /etc/hosts /etc/hosts.bkp"
		);
		return $rs if ($rs != 0);
	}

	my $data  = "# 'hosts' file configuration.\n\n";

	$data .= "127.0.0.1\t$hostname_local\tlocalhost\n";
	$data .= "$ip\t$hostname\t$host\n";
	$data .= "::ffff:$ip\t$hostname\t$host\n";
	$data .= "::1\tip6-localhost ip6-loopback\n";
	$data .= "fe00::0\tip6-localnet\n";
	$data .= "ff00::0\tip6-mcastprefix\n";
	$data .= "ff02::1\tip6-allnodes\n";
	$data .= "ff02::2\tip6-allrouters\n";
	$data .= "ff02::3\tip6-allhosts\n";

	my $rs = store_file(
		'/etc/hosts', $data, $main::cfg{'ROOT_USER'}, $main::cfg{'ROOT_GROUP'},
		0644
	);
	return $rs if ($rs != 0);

	push_el(\@main::el, 'setup_hosts()', 'Ending...');

	0;
}

################################################################################
#                            High level subroutines                            #
################################################################################

################################################################################
# Starting setup process
#
# @return void
#
sub setup_start_up {

	push_el(\@main::el, 'setup_start_up()', 'Starting...');

	# Fixing umask for log files permissions (0640)
	umask(027);

	system('clear');
	spacer();

	welcome_note();

	push_el(\@main::el, 'setup_start_up()', 'Ending...');
}

################################################################################
# Processing all setup tasks
#
# @return void
#
sub setup_engine {

	push_el(\@main::el, 'setup_engine()', 'Starting...');

	# Starting user dialog
	user_dialog();

	system('clear');
	spacer();

	# Starting ispCP installation
	title('Starting ispCP installation');

	# Stopping services
	subtitle('Stopping all services: ');
	stop_services();
	print_status(0);

	# Starting dist. maintainer pre-installation script if one exists
	if(-e "$main::cfg{'ROOT_DIR'}/engine/setup/preinst") {
		spacer();

		title("Pre-installation tasks for $main::cfg{'DistName'}");
		my $rs = preinst('install');
		exit_msg($rs) if ($rs != 0);
	}

	spacer();

	# Checking host system (Currently, only DB connection)
	title('System checks');
	check_host_system();

	spacer();

	# Setting host system
	title('Services setup');
	setup_services_cfg();

	spacer();

	# Starting GUI configuration
	title('GUI setup');
	setup_gui_cfg();

	spacer();

	# Starting dist. maintainer post-installation script if one exists
	if(-e "$main::cfg{'ROOT_DIR'}/engine/setup/postinst") {
		spacer();

		title("Post-installation tasks for $main::cfg{'DistName'}");
		my $rs = postinst('configure');
		exit_msg($rs) if ($rs != 0);
	}

	spacer();

	title('Permissions setup');
	set_permissions();

	spacer();

	title('Finishing installation');

	# Starting services
	subtitle('Starting all services: ');
	start_services();
	print_status(0);

	spacer();

	# Additional tasks
	title('Additional tasks');
	additional_tasks();

	push_el(\@main::el, 'setup_engine()', 'Ending...');

	0;
}

################################################################################
# Shutting down setup process
#
# @return int 0 on success, other on failure
#
sub setup_shut_down {

	push_el(\@main::el, 'setup_shut_down()', 'Starting...');

	print colored( ['bold underline'],
		"\n\tCongratulations you installed ispCP '$main::cfg{'Version'}' " .
		"successfully!\n\n"),

		"\tPlease type http://$main::ua{'admin_vhost'} in your browser and\n" .
		"\tlog in with your Administrator Account to use ispCP.\n\n";

	push_el(\@main::el, 'setup_shut_down()', 'Ending...');
}

################################################################################
#                                Main program                                  #
################################################################################

setup_start_up();
setup_engine();
setup_shut_down();

exit 0;
