#!/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-ispcp 2890 2010-04-27 22:43:12Z 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
#

$main::db_pwd = undef;
$main::db_user = undef;

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

use strict;
use warnings;

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

sub lock_backup_ispcp_system {

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

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

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

	if (-e $backup_lock_file) {

		push_el(\@main::el, 'lock_backup_ispcp_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_ispcp_system()', 'Ending...');

	return 0;
}


sub unlock_backup_ispcp_system {

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

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

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

	return 0;

}



sub backup_ispcp_start_up {

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

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

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

	# config check;

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

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

	return 0;

}


sub backup_ispcp_shut_down {

	my $rs = undef;

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

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

	push_el(\@main::el, 'backup_ispcp_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);

	backup_ispcp_shut_down();

	print STDERR "$msg\n";

	exit 1;

}

sub backup_ispcp_mail_task {

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

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

	my $date = get_human_date();

	my $admin_email = $main::cfg{'DEFAULT_ADMIN_ADDRESS'};

	my $backup_dir = $main::cfg{'BACKUP_FILE_DIR'};

	my $backup_file_list = `ls -la $backup_dir`;

	my $server_name = $main::cfg{'SERVER_HOSTNAME'};

	my $server_ip = $main::cfg{'BASE_SERVER_IP'};

	my $msg_data = <<MESSAGE_TEXT;
Hey There,

I'm the automatic backup system on your $server_name ($server_ip) server.

Backup task was completed successfully!

File(s) List In ($backup_dir):

========================================================================
$backup_file_list
========================================================================
MESSAGE_TEXT

	my $out = new MIME::Entity;

	$out -> build(
				From => "Automatic Backup Manager <".$admin_email.">",
				To => $admin_email,
				Subject => "[$date] Backup report.",
				Data => $msg_data,
				'X-Mailer' => "ispCP $main::cfg{'Version'} Automatic Backup Messenger"
				);

	open MAIL, "| /usr/sbin/sendmail -t -oi";

	$out -> print(\*MAIL);

	close MAIL;

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

	return 0;

}

sub backup_ispcp_database {

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

	my $rs				= undef;
	my ($date)			= @_;
	my $dbpass			= $main::db_pwd;
	my $db_name			= $main::cfg{'DATABASE_NAME'};
	my $zip				= $main::cfg{'ZIP'};
	my $backup_dir		= $main::cfg{'BACKUP_FILE_DIR'};

	my $db_backup_file	= "$backup_dir/$db_name-$date.sql";

	$dbpass =~ s/([\''])/\\$1/g;

	my $db_backupcmd = "$main::cfg{'CMD_MYSQLDUMP'} --add-drop-table --allow-keywords --quote-names -h'$main::cfg{'DATABASE_HOST'}' -u'$main::db_user' -p'$dbpass' '$db_name' >'$db_backup_file'";
	my ($db_filename, $db_compresscmd) = (undef, undef);

	if ($zip eq "bzip2") {
		$db_filename = "$db_backup_file.bz2";
		$db_compresscmd = "$main::cfg{'CMD_BZIP'} --force \'$db_backup_file\'";
	} elsif ($zip eq "gzip") {
		$db_filename = "$db_backup_file.gz";
		$db_compresscmd = "$main::cfg{'CMD_GZIP'} --force \'$db_backup_file\'";
	} elsif ($zip eq "lzma") {
			$db_filename = "$db_backup_file.lzma";
			$db_compresscmd = "$main::cfg{'CMD_LZMA'} --force \'$db_backup_file\'";
	} else {
		push_el(\@main::el, 'backup_ispcp_database()', "Backup algorithm not supported: $zip");
		return 1;
	}

	$rs = sys_command($db_backupcmd);
	if( $rs != 0 ){
		push_el(\@main::el, 'backup_ispcp_database()', "ERROR: Failed to backup database $db_name!");
		send_error_mail('backup_ispcp_database()', "ERROR: Failed to backup database $db_name!");
		unlink($db_backup_file);
		return -1;
	}

	$rs = setfmode("$db_backup_file", 0, 0, 0640);
	if ($rs != 0) {
		push_el(\@main::el, 'backup_ispcp_database()', "ERROR: Failed to backup chmod 0640 user root group root file $db_backup_file!");
		send_error_mail('backup_ispcp_database()', "ERROR: Failed to backup chmod 0640 user root group root file $db_backup_file!");
		unlink($db_backup_file);
		return -1;
	}

	$rs = sys_command($db_compresscmd);
	if ($rs != 0) {
		push_el(\@main::el, 'backup_ispcp_database()', "ERROR: Failed to compress database $db_name!");
		send_error_mail('backup_ispcp_database()', "ERROR: Failed to compress database $db_name!");
		unlink($db_backup_file);
		return -1;
	}

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

	return 0;
}

sub backup_ispcp_engine {

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

	my ($backup_filename, $backup_cmd) = (undef, undef);

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

	my $cmd_tar = $main::cfg{'CMD_TAR'};
	my $cmd_rm = $main::cfg{'CMD_RM'};
	my $cmd_mv = $main::cfg{'CMD_MV'};

	my $conf_dir = $main::cfg{'CONF_DIR'};
	my $backup_dir = $main::cfg{'BACKUP_FILE_DIR'};
	my $zip = $main::cfg{'ZIP'};

	my $date = get_human_date();

	# Backup of configuration files (/etc/ispcp), preparation

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

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

		$backup_filename = "config-backup-$date.tar." . $extension;
		$backup_cmd = "$cmd_tar --create --directory=$conf_dir --$zip --file=$backup_dir/$backup_filename . 2> $main::cfg{'LOG_DIR'}/$backup_filename.log";

	} else {
		push_el(\@main::el, 'backup_ispcp_engine()', "Backup algorithm not supported: $zip!");
		send_error_mail('backup_all_engine()', "Backup algorithm not supported: $zip!");
		return -1;
	}

	if(! -d $backup_dir) {
		$rs = make_dir($backup_dir, 0, 0, 0750);
		return $rs if ($rs != 0);
	}

	# DB backup
	$rs = backup_ispcp_database($date);

	# do the config backup
	$rs = sys_command($backup_cmd);

	if ($rs == 0) {

		$rs = sys_command("$cmd_rm -rf $main::cfg{'LOG_DIR'}/$backup_filename.log");
		return $rs if ($rs != 0);

	} elsif ( -e "$backup_dir/$backup_filename" ) {

		$rs = del_file("$backup_dir/$backup_filename");
		return $rs if ($rs != 0);

	}

	# remove old backups: >14 days old
	sys_command("find $backup_dir/* -maxdepth 0 -type f -mtime +14 -print | xargs -r /bin/rm");

	$rs = setfmode("$backup_dir/$backup_filename", 0, 0, 0640);
	return $rs if ($rs != 0);

	push_el(\@main::el, 'backup_ispcp_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) (report|noreport)!");
	err_exit();

}

if ($proceed ne 'report' && $proceed ne 'noreport' ) {

	push_el(\@main::el, 'main()', "NOTE: If you want to be notified when the backup is done, please run this script with 'report' as command line parameter, otherwise with 'noreport'");
	err_exit();

}


$rs = backup_ispcp_start_up();
err_exit() if ($rs != 0 && $rs != 2);
exit 0 if ($rs == 2); # $rs == 2 when backups are disabled

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

if ($proceed eq 'report') {
	$rs = backup_ispcp_mail_task();
	err_exit() if ($rs != 0);
}

$rs = backup_ispcp_shut_down($backup_lock_file);
err_exit() if ($rs != 0);

exit 0;
