#!/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-backup-all 3476 2010-10-16 22:37:41Z scitech $
#
# 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
#

use FindBin;
use lib "$FindBin::Bin/..";
require 'ispcp_common_code.pl';

use strict;
use warnings;

our $backup_lock_file = "/tmp/ispcp-backup-all.lock";

sub lock_backup_all_system {

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

	if ($main::cfg{'BACKUP_DOMAINS'} ne 'yes') {

		push_el(\@main::el, 'lock_backup_all_system()', 'NOTICE: domain backups are disabled');
		return 2;
	}

	if (-e $backup_lock_file) {

		push_el(\@main::el, 'lock_backup_all_system()', 'ERROR: backup request engine already locked!');
		return 1;

	}

	my $touch_cmd = "$main::cfg{'CMD_TOUCH'} $backup_lock_file";

	my $rs = sys_command($touch_cmd);
	return 1 if ($rs != 0);

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

	return 0;
}


sub unlock_backup_all_system {

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

	my $rs = del_file($backup_lock_file);
	return $rs if ($rs != 0);

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

	return 0;

}


sub backup_all_start_up {

	my ($rs, $rdata) = (undef, undef);

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

	$rs = lock_backup_all_system();
	return $rs if ($rs != 0);

	# config check;

	$rs = get_conf();
	return $rs if ($rs != 0);

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

	return 0;

}


sub backup_all_shut_down {


	my $rs = undef;

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

	$rs = unlock_backup_all_system();
	return $rs if ($rs != 0);

	push_el(\@main::el, 'backup_all_shut_down()', 'Ending...');
	return 0;

}


sub err_exit {

	my $el_data = pop_el(\@main::el);

	$main::el_sep = "\t#\t";

	my ($sub_name, $msg) = split(/$main::el_sep/, $el_data);

	print STDERR "$msg\n";

	unlock_backup_all_system($backup_lock_file);
	exit 1;

}

sub backup_sql {

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

	my ($dmn_id, $dmn_name, $domain_uid, $domain_gid) = @_;
	my $zip = $main::cfg{'ZIP'};
	my ($rs, $rdata, $sql) = (undef, undef, undef);

	my $dmn_backup_dir = $main::cfg{'APACHE_WWW_DIR'}."/$dmn_name/backups";
	my $dbhost = $main::cfg{'DATABASE_HOST'};
	my $dbuser = $main::cfg{'DATABASE_USER'};
	my $dbpass = decrypt_db_password($main::cfg{'DATABASE_PASSWORD'});

	foreach ($dbhost, $dbuser, $dbpass) {
		$_ =~ s/"/\\"/gm;
	}

	$sql = "SELECT `sqld_id`, `sqld_name` FROM `sql_database` WHERE `domain_id`='$dmn_id'";
	($rs, $rdata) = doSQL($sql);

	foreach (@$rdata) {

		my $db_id = @$_[0];
		my $db_name = @$_[1];
		my $db_backup_file = "$dmn_backup_dir/$db_name.sql";
		my ($db_filename, $db_compresscmd) = (undef, undef);
		my $dbname = $db_name;
		my $dbbackup = $db_backup_file;

		$dbname =~ s/"/\\"/g;
		$dbbackup =~ s/"/\\"/g;

		my $db_backupcmd = "$main::cfg{'CMD_MYSQLDUMP'} --add-drop-table --allow-keywords --quote-names";
		$db_backupcmd .= qq/ -h'$dbhost' -u'$dbuser' -p'$dbpass' '$dbname' > '$dbbackup'/;

		if ($zip eq "bzip2") {
			$db_filename = "$dbbackup.bz2";
			$db_compresscmd = $main::cfg{'CMD_BZIP'}.qq/ --force '$dbbackup'/;
		} elsif ($zip eq "gzip") {
			$db_filename = "$dbbackup.gz";
			$db_compresscmd = $main::cfg{'CMD_GZIP'}.qq/ --force '$dbbackup'/;
		} elsif ($zip eq "lzma") {
			$db_filename = "$dbbackup.lzma";
			$db_compresscmd = $main::cfg{'CMD_LZMA'}.qq/ --force '$dbbackup'/;
		} else {
			push_el(\@main::el, 'backup_sql()', "Domain $dmn_name: Backup algorithm for domain $dmn_name not supported: $zip!");
			send_error_mail('backup_sql()', "Domain $dmn_name: Backup algorithm for domain $dmn_name not supported: $zip!");
			return -1;
		}

		$rs = sys_command_rs($db_backupcmd);
		if($rs != 0) {
			push_el(\@main::el, 'backup_sql()', "Domain $dmn_name: ERROR: Failed to backup database $db_name!");
			send_error_mail('backup_sql()', "Domain $dmn_name: ERROR: Failed to backup database $db_name!");
			unlink($db_backup_file);
			return $rs;
		}

		$rs = setfmode("$db_backup_file", $main::cfg{'ROOT_USER'}, $main::cfg{'ROOT_GROUP'}, 0444);
		if($rs != 0) {
			push_el(\@main::el, 'backup_sql()', "Domain $dmn_name: ERROR: Can not chmod 0444 root:root file $db_backup_file!");
			send_error_mail('backup_sql()', "Domain $dmn_name: ERROR: Can not chmod 0444 root:root file $db_backup_file!");
			unlink($db_backup_file);
			return $rs;
		}

		$rs = sys_command($db_compresscmd);
		if ($rs != 0) {
			push_el(\@main::el, 'backup_sql()', "Domain $dmn_name: ERROR: Error while executing  $db_compresscmd!");
			send_error_mail('backup_sql()', "Domain $dmn_name: ERROR: Error while executing $db_compresscmd!");
			unlink($db_backup_file);
			return $rs;
		}

	}

	push_el(\@main::el, 'backup_sql()', 'Ending...');
	return 0;
}

sub backup_all_engine {

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

	my ($rs, $rdata, $sql) = (undef, undef, undef);
	my $zip = $main::cfg{'ZIP'};

	$sql = "
		SELECT
			t1.domain_id,
			t1.domain_name,
			t1.domain_status,
			t1.domain_uid,
			t1.domain_gid,
			t1.allowbackup,
			t2.admin_name,
			t2.email
		FROM
			domain AS t1,
			admin AS t2
		WHERE
				t1.domain_status	= 'ok'
			AND	t1.domain_admin_id	= t2.admin_id
			AND 	t1.allowbackup		!= 'no'
		ORDER BY
			t1.domain_id
	";

	($rs, $rdata) = doSQL($sql);
	return $rs if ($rs != 0);

	my $cmd_tar = $main::cfg{'CMD_TAR'};

	my $cmd_rm = $main::cfg{'CMD_RM'};

	my $cmd_mv = $main::cfg{'CMD_MV'};

	my $httpd_uid = $main::cfg{'APACHE_USER'};

	my $httpd_gid = $main::cfg{'APACHE_GROUP'};

	foreach (@$rdata) {

	# DO NOT RETURN, even if backup throws an error, otherwise other domains will not be backuped
	# I DO MEAN IT :)

		my ($dmn_id, $dmn_name, $dmn_status, $domain_uid, $domain_gid, $allowbackup, $admin_name, $admin_email) = (@$_[0], @$_[1], @$_[2], @$_[3], @$_[4], @$_[5], @$_[6], @$_[7]);

		if ($allowbackup eq "full" || $allowbackup eq "dmn" || $allowbackup eq "sql") {

			my $date = get_human_date();
			my $www_dir = $main::cfg{'APACHE_WWW_DIR'};
			my $dmn_dir = $main::cfg{'APACHE_WWW_DIR'}."/$dmn_name";
			my $dmn_backup_dir = $main::cfg{'APACHE_WWW_DIR'}."/$dmn_name/backups";
			my ($backup_filename, $backup_cmd) = (undef, "");

			#
			# User Database Backup
			#

			if (! -d $dmn_backup_dir) {
				$rs = make_dir($dmn_backup_dir, $main::cfg{'ROOT_USER'}, $main::cfg{'ROOT_GROUP'}, 0755);
				return $rs if ($rs != 0);
			}

			$rs = setfmode($dmn_backup_dir, $main::cfg{'ROOT_USER'}, $main::cfg{'ROOT_GROUP'}, 0755);
			if ($rs != 0) {
				push_el(\@main::el, 'backup_all_engine()', "Domain $dmn_name: Error while changing mode to 0755 root: root for $dmn_backup_dir!");
				send_error_mail('backup_all_engine()', "Domain $dmn_name: Error while changing mode to 0755 root: root for $dmn_backup_dir!");
			}

			if ($zip =~ '^(bzip2|gzip|lzma|xz)$') {
				my $extension = undef;

				if ($zip eq 'bzip2') {
					$extension = 'bz2';
				} else {
					$extension = $zip;
				}

				$backup_filename = "$dmn_name-backup-$date.tar." . $extension;
				if ($allowbackup eq "full" || $allowbackup eq "dmn") {
					$backup_cmd = "$cmd_tar --create --directory=$dmn_dir --$zip --file=$www_dir/$backup_filename --exclude=logs --exclude=phptmp --exclude=backups . 2> $www_dir/$backup_filename.log";
				}
				if ( $allowbackup eq "full" || $allowbackup eq "sql" ) {
					$rs = backup_sql($dmn_id, $dmn_name, $domain_uid, $domain_gid);
				}
			} else {
				push_el(\@main::el, 'backup_all_engine()', "Backup algorithm not supported: $zip for domain $dmn_name!");
				send_error_mail('backup_all_engine()', "Backup algorithm not supported: $zip for domain $dmn_name!");
			}

			if (length($backup_cmd) != 0 ) {
				$rs = sys_command($backup_cmd);

				if ($rs == 0) { # everything ok

					$rs = sys_command("$cmd_rm -rf $www_dir/$backup_filename.log");
					if ($rs != 0) {
						push_el(\@main::el, 'backup_all_engine()', "Domain $dmn_name: Error while executing $cmd_rm -rf $www_dir/$backup_filename.log!");
						send_error_mail('backup_all_engine()', "Domain $dmn_name: Error while executing $cmd_rm -rf $www_dir/$backup_filename.log!");
					}

					$rs = sys_command("$cmd_rm -rf $dmn_backup_dir/$dmn_name-*.tar.*");
					if ($rs != 0) {
						push_el(\@main::el, 'backup_all_engine()', "Domain $dmn_name: Error while executing $cmd_rm -rf $dmn_backup_dir/$dmn_name-*.tar.*!");
						send_error_mail('backup_all_engine()', "Domain $dmn_name: Error while executing $cmd_rm -rf $dmn_backup_dir/$dmn_name-*.tar.*!");
					}

					$rs = sys_command("$cmd_mv -f $www_dir/$backup_filename $dmn_backup_dir");
					if ($rs != 0) {
						push_el(\@main::el, 'backup_all_engine()', "Domain $dmn_name: Error while executing $cmd_mv -f $www_dir/$backup_filename $dmn_backup_dir!");
						send_error_mail('backup_all_engine()', "Domain $dmn_name: Error while executing $cmd_mv -f $www_dir/$backup_filename $dmn_backup_dir!");
					}

					$rs = setfmode("$dmn_backup_dir/$backup_filename", $main::cfg{'ROOT_USER'}, $main::cfg{'ROOT_GROUP'}, 0444);
					if ($rs != 0) {
						push_el(\@main::el, 'backup_all_engine()', "Domain $dmn_name: Error while changing mode to 0444 root:root for $dmn_backup_dir/$backup_filename!");
						send_error_mail('backup_all_engine()', "Domain $dmn_name: Error while changing mode to 0444 root:root for $dmn_backup_dir/$backup_filename!");
					}

				} else { # some error occurred

					push_el(\@main::el, 'backup_all_engine()', "Domain $dmn_name: ERROR: tar returned exit status $rs, have a look in $www_dir/$backup_filename.log");
					# send mail so we know something went wrong...
					send_error_mail('backup_all_engine()', "Domain $dmn_name: ERROR: tar returned exit status $rs, have a look in $www_dir/$backup_filename.log");

					# delete backup file...
					if ( -e "$www_dir/$backup_filename" ) {
						$rs = del_file("$www_dir/$backup_filename");
						if ($rs != 0) {
							push_el(\@main::el, 'backup_all_engine()', "Domain $dmn_name: Error while removing file $www_dir/$backup_filename!");
# we don't need a second mail...			send_error_mail('backup_all_engine()', "Domain $dmn_name: Error while removing file $dmn_dir/$backup_filename!");
						}
					}

				}
			}
		} else {
			push_el(\@main::el, 'backup_all_engine()', "Domain $dmn_name: ERROR: the type of backup (*$allowbackup*) is not allowed!");
		}
	}

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

	return 0;

}

my $rs = undef;
my $proceed = $ARGV[0];

if (!defined($proceed) || $proceed eq '') {

	push_el(\@main::el, 'main()', "ERROR: Missing Input Data! Please provide appropriate command line parameter(s)!");

	err_exit();

}

if ($proceed ne 'yes') {

	push_el(\@main::el, 'main()', "NOTICE: If you want full backup of your domain data, please run this script with 'yes' command line parameter!");

	err_exit();

}

$rs = backup_all_start_up();
err_exit() if ($rs != 0 && $rs != 2);

exit 0 if ($rs == 2); # $rs == 2 when backups are disabled

$rs = backup_all_engine();
err_exit() if ($rs != 0);

$rs = backup_all_shut_down();
err_exit() if ($rs != 0);

exit 0;
