#!/usr/bin/perl
###########
# rrbackups
# Restores all cPanel backups found in top level of user's homedir. See --help for more.
# http://git.toolbox.hostgator.com/rrbackups/pages/Home 
# http://git.toolbox.hostgator.com/rrbackups/rrbackups
# Please submit all bug reports at bugs.hostgator.com
#
# (C) 2011-2012 - HostGator.com, LLC
###########

## Will restore all cPanel backups found in user's homedir (mindepth/maxdepth 1)
## Specify reseller with --reseller flag followed by the username.  See --help for more info.

#
# MILESTONE - 100% feature complete compared to bash version - 10/26/11
#

# Feature requests/ideas, in somewhat order of priority:
#
# - save pre-restore and post-restore UI results to log files for later review
#
# Completed feature requests/ideas
# - give an option to backup all reseller's accounts - work in progress - 09/28/11 - DONE! - 10/03/11
# - Use regex MATCHING ($1, $2, etc.), instead of splitting $backups - 09/16/11 - DONE! - 10/03/11
# - check if backups found are zero/null, output error if so. - 10/10/11 - DONE - 10/14/11
# - existaccount check subroutine - 10/25/11 - DONE! - 10/26/11
# - post restore checks!  ADD THEM NAOW - 10/06/11 - DONE! - 10/26/11
# - fixed mysqldbrepair subroutine - 10/18/11 - DONE! - 10/26/11
# - When listing or processing backups, store as hash instead of array,
#   so that you can show multiple backups per user if present, and give option on
#   which one to restore (and maybe in the future present an option to restore the
#   newest?) - 09/17/11 - DONE (sort of) uses hashes and uses most recent backup
#   (see --help for details) - 11/07/11
# - implement in Perl (first attempt: 09/13/11) - work in progress - 09/28/11 - 100% feature complete (see milestone) - 10/28/11
# - Log executed commands to a log file.  Example:  running /scripts/restorepkg,
#   store it in a log file for later review/let user of script know where file is
#   when done running each restore// completed running all restores - 09/28/11 - DONE! - 11/07/11
# - --backuplist=file only works with --listbackups, otherwise doesn't detect any backups in the file, and for some reason calls &backups when it shouldn't be -- 11/10/11 - DONE! - 11/10/11
# - detect if running in screen (use $ENV{"TERM"} value), and if not, recommend restarting the software in screen
#	and possibly give the option to restart the software in screen instead -- DONE! - 11/11/11
# - bug in IP check post/pre-restore:  The &preexistingacctpostrestorecheck doesn't run at all!  FIX - 12/21/11 - FIXED (last week) - 01/02/12
# - subroutines/processes for restoring a single shared user - NEED TO ADD ABILITY TO MOVE BACKUP SO IT ISN'T REMOVED DURING KILLACCT IF IT IS STORED IN THE SAME DIRECTORY AS ACCOUNT BEING KILLED - 01/04/12 - DONE - 01/05/12
# - interrupt handling - 01/02/12 - some done (SIGINT) - 01/05/12
# - detect what PLAN is in use on existing account, save it, then restore the PLAN as part of
#   &preexistingpostrestorecheck(s) (var/cpanel/users/user:PLAN=planname) - DONE - 01/06/12

# what I was last working on:

# - try to get this working to get quota without doing a system call to quota:
#
	#my $uid = &getuidofuser($backupuser);
	#my ($bc, $bs, $bh, $bt, $ic, $is, $ih, $it) = Quota::query(Quota::getqcarg(&homedir($backupuser)), $uid);
	#&printh("Quota example: "); print Quota::query(Quota::getqcarg(&homedir($backupuser)), $uid); exit 0;
	#&printe("Quota data for $backupuser, uid $uid: \$bc $bc : \$bs $bs :: \$ic $ic : \$is $is\n");
#
# - get pre-restore backups list working as always outputs "No pre-restore backups created" regardless if there are any - 11/04/11
# - debug script as a whole - 10/26/11

# Notes:
# better UI to use: perl <(GET hgfix.net/transfer/ui.php) maybe?

use strict;
use warnings;
#use autodie; # testing only

use DBI;
use File::Find;
use Sys::Hostname;
use POSIX qw/strftime/;
use Term::ANSIColor;
use File::Basename;
use File::HomeDir;
use LWP::Simple;
use Cwd;
use File::Copy;
#use Quota;

my (@backups, @backupscompleted, @backupsfailed, @restorescompleted,  @restoresfailed, @prerestorebackups, @killacctfailed);
my (%backups, %dupebackups, %nondupebackups, %seenuser, @sumysqlusers);

my ($logdir, $logfile, $ui, $backup, $owner, $backupdir, $backupfile,  $backuplistfile, $backupuser, $originalip, $originalplan);

my %conf = (
	version 	=> '1.0',
	nicevalue 	=> '15',
	date 		=> strftime("%m.%d.%y_%H-%M-%S", localtime),
	scriptname 	=> basename($0),
	scriptdir 	=> dirname($0),
	newui		=> '/tmp/rrbackups-ui',
	nice		=> '/bin/nice -n'
);

my %rrbackup;

$conf{'header'} = "Restore Reseller Backups $conf{'version'} : Mark Shields, mshields\@hostgator.com";

$conf{'killacct'}	= "perl /scripts/killacct --killdns";
$conf{'pkgacct'}	= "perl /scripts/pkgacct --userbackup";
$conf{'restorepkg'}	= "perl /scripts/restorepkg --skipres";

my @arguments = @ARGV;
local @ARGV = ();


&begin(@arguments); # it all starts here, buddy!


sub accountinfo { # works - 09/16/11
	my ($backupuser) = @_;
	my $uiscript = "/root/bin/ui";
	# check for $uiscript, exit 1 if not
	&printe("$uiscript not available! Install and try again.\n") if ! -s $uiscript;
	# collect info needed post-restore, original IP and PLAN
	$originalip = &cpuserip($backupuser);
	$originalplan = &cpuserplan($backupuser);

	&prints("Account Information\n");
		
	open my $uifile, "<", $uiscript
		or die "Unable to open $uiscript for reading: $1";
	my @lines = <$uifile>;
	close $uifile;
	foreach (@lines) {
		if ( /perl/ ) {
			$rrbackup{'uiused'} = "perl";
			$ui = `perl $uiscript $backupuser`;
			last;
		}
		elsif ( /bash/ ) {
			open my $bashui, "<", $uiscript || &printe("Unable to open $uiscript for reading!\n");
			my @lines = <$bashui>;
			close $bashui;
			open my $newuifile, ">", $conf{'newui'} || &printe("Unable to open $conf{'newui'} for writing!\n");
			foreach (@lines) {
				print $newuifile $_ if (!/clear/);
			}
			close $newuifile;
			$rrbackup{'uiused'} = "bash";
			$ui = `bash $conf{'newui'} $backupuser`;
			last;
		}
		else { &printe("Unable to determine if $uiscript is a Perl or Bash script.  Reinstall and try again.\n"); }
	}
	print $ui;
	&printh("The above information is important!  Copy it to ticket notes or a safe place.\n");
	if ( &continuequery == 0 ) { print "\n"; &printe("Restore incomplete!  Please run the restore again.\n    Exiting due to user declining to continue.\n\n"); }
	return;
}

sub backupacct { # needs a valid user, for backing up a single account
	my ($backupuser) = @_;
	print "\n";
	&printb("Starting backup process for user '$backupuser'\n");
	&mysqldbrepair($backupuser); # repair all dbs
	&perms($backupuser, "permissions.log");

	# we redefine SIGINT here to keep this script from being interrupted while restore is happening
	local $SIG{'INT'} = 'IGNORE';

	# then do the actual backup...
	$logfile = "$logdir/$backupuser-pkgacct.log";
	
	print "\n";	
	&printb("Backing up account: ", color('bold white'), "$backupuser\n", color('bold blue'),"    to -> ", color('yellow'), "$backupdir/...\n\n");
	&printb("Log file will be stored:\n    at -> ", color('yellow'), "$logfile\n");
	print "\n"; &largewarning;
	# WORKING (doesn't work though, see notes for quota - 01/05/11)
	
	my @log = `$conf{'nice'} $conf{'nicevalue'} $conf{'pkgacct'} $backupuser $backupdir 2>&1` || &printe("Backup failed.  The cPanel user may be incomplete -- homedir may be missing, for example.\n"); # backup failure!
	open my $logfileout, ">>", $logfile
		or die "Can't write to log file: $!";
	print {$logfileout} $_ foreach (@log);
	close $logfileout;

	open my $logfilein, "<", $logfile
		or die "Can't open log file $logfile for reading: [$!]";
	my @logfilein = <$logfilein>;
	close $logfilein;

	my $pkgacctmatch;
	foreach(@logfilein) { if (/^pkgacctfile is: (.*)/) { $pkgacctmatch = $1; last; }}
	if (defined($pkgacctmatch)) { print "\n"; &printb("Pkgacct appears to have successfully completed, created backup:\n    at -> $pkgacctmatch\n\n"); } 
	else { &printh("Pkgacct failed!  Please review the logfile:\n    at -> $logfile\n"); }
	&prints("Backup for user '$backupuser' finished.\n");
	push(@backupscompleted, $pkgacctmatch);
	print "\n";
	
	local $SIG{'INT'} = \&catchsigint;

	return;
}

sub backupall { 
	($rrbackup{'reselleruser'}) = @_;
	if ( &resellercheck($rrbackup{'reselleruser'}) == 0 ) {
		my @backupallusers;
		my $file="/etc/trueuserowners";
		open my $trueuserowners, "<", $file || &printe("Unable to open $file!\n");
		while (<$trueuserowners>) {
			if (/^([a-z0-9]{1,8}): $rrbackup{'reselleruser'}$/) {
				push @backupallusers, $1;
			}
		}
		close $trueuserowners;
		print "\n";
		&printb("Here are the users I will attempt to backup:\n\n");
		&printe("No users to backup! Exiting.\n") if (@backupallusers == 0);
		@backupallusers = sort @backupallusers;
		if (@backupallusers < 20) { print "\t $_\n" foreach (@backupallusers); }
		else { print "\t $_  " foreach (@backupallusers); }

		print "\n";
		&printb("This process will backup '", scalar @backupallusers, "' accounts.\n");
		exit 0 if ( &continuequery == 0);
		foreach (@backupallusers) { chomp($backupuser = $_); &backupacct($backupuser); }

		&prints("Backup finished for all accounts under reseller $rrbackup{'reselleruser'}.  Please review the list below of all backup files present:\n\n");
		print "\t$_\n" foreach(sort @backupscompleted);
		print "\n";
		&printb("Log files can be found:\n    at -> $logdir\n\n");
		&printh("These backups are not accessible by the reseller; please move and change permissions/ownership as necessary.\n");
		exit 0;
	}
	return;
}
 
sub backups {
	my $resellerhome = &homedir($rrbackup{'reselleruser'});
	if ( &resellercheck($rrbackup{'reselleruser'}) == 0 ) {
		opendir (my $dh, $resellerhome) or die "Can't open $resellerhome: $!";
		my @backupswithoutdir;
		push @backupswithoutdir, grep { /^(cpmove-)?[a-z0-9]{1,8}(.tar(.gz)?)?\b/ && -f "$resellerhome/$_" } readdir($dh);
		push @backupswithoutdir, grep { /^backup-(1[0-2]|\d)\.([1-9]|[12]\d|3[01])\.2\d{3}_(\d{2})-(\d{2})-(\d{2})_[a-z0-9]{1,8}.tar(.gz)?\b/ && -f "$resellerhome/$_" } readdir($dh);
		close $dh;
		# exclude backups with the $rrbackup{'reselleruser'} present
		@backupswithoutdir = grep { ! /$rrbackup{'reselleruser'}/ } @backupswithoutdir;
		foreach (sort @backupswithoutdir) { push(@backups, "$resellerhome/$_"); }
		if ((@backups) and (!$backuplistfile)) { &dupefinder(@backups, $resellerhome); return 1; }
		else { &printe("No compatible backups found in $resellerhome. Please check and try again.\n"); }
	}
	else { &printe("Invalid reseller, $rrbackup{'reselleruser'}.  Problem?\n"); }
	return;
}

sub begin { # main subroutine
	my (@arguments) = @_;
	
	# let's get some interrupt handling going - 01/05/11
	
	local $SIG{'INT'} = \&catchsigint;

	local $ENV{'ANSI_COLORS_DISABLED'} = 1 if grep { /^(--nocolor|-nc)$/ } @arguments or ! -t *STDOUT;
	&versioncheck(@arguments);
	&printb("\n$conf{'header'}\n");
	&helpcheck(@arguments);
	&prerunchecks;
	# run &options first, it will return $rrbackup{'reselleruser'} if it finishes
	&rrbackups(&options(@arguments));
	return;
} # end main subroutine

sub catchsigint {
	print "\n\n";
	&printe("Caught SIGINT! Exiting...\n\n");
	return;
}

sub checkownerofcpaneluser {
	my ($user) = @_;
	die "No user passed to checkownerofcpaneluser subroutine: $!" if !defined($user);
	open my $checkowner, "<", "/var/cpanel/users/$user" || &printe("Unable to open user's cPanel file.  Aborting!\n");
	undef $owner;
	while (my $line = <$checkowner>) {
		if ( $line =~ /^OWNER=([a-z0-9]{1,8})$/ ) {
			$owner = $1;
			last;
		}	
	}
	close $checkowner;
	$owner = 'invalid' if ! $owner;
	return $owner;
}

sub checkresetbwdiskquotas {
	my ($bwlimit, $dulimit) = @_;
	&printb("Resetting bandwidth quota to $bwlimit\n"); 
	open my $cpfilein, "<", "/var/cpanel/users/$backupuser" or &printe("Unable to open cPanel user file!\n");
	my @lines = <$cpfilein>;
	close $cpfilein;
	open my $cpfileout, ">", "/var/cpanel/users/$backupuser" or &printe("Unable to open cPanel user file!\n");
	foreach (@lines) {
		s/^BWLIMIT=.*/BWLIMIT=$bwlimit/;
		print {$cpfileout} $_;
	}
	close $cpfileout;
	&printb("Resetting disk quota to $dulimit\n"); &logtofile("$conf{'nice'} $conf{'nicevalue'} /scripts/editquota $backupuser $dulimit 2>&1", "$backupuser-editquota.log");
	return;
}

sub continuequery {
	my $defaultanswer = 'yes';
	&printq("Continue? [$defaultanswer] : ");
	LINE: while(my $answer = <>) {
		if ( $answer =~ /^(yes|y)$/i ) 		{	return 1; }
		elsif ( $answer =~ /^(n(o)?)$/i ) 	{	return 0; }
		elsif ( $answer =~ /^$/ ) 			{	return 1; }
		else { chomp($answer); &printh("Invalid entry, \"$answer\".  Type yes or no [$defaultanswer] : "); }
	}
	return;
}

sub cpuserip { # takes cPanel/linux username as argument
	my ($cpuser) = @_;
	my $ip;
	open my $cpfile, "<", "/var/cpanel/users/$cpuser" || &printe("Unable to open /var/cpanel/users/$cpuser!");
	while (<$cpfile>) { if ( /^IP=(.*)$/ ) { $ip = $1; last; }}
	close $cpfile;
	return $ip;
}

sub cpuserplan { # takes cPanel/linux username as argument
	my ($cpuser) = @_;
	my $plan;
	open my $cpfile, "<", "/var/cpanel/users/$cpuser" || &printe("Unable to open /var/cpanel/users/$cpuser!");
	while (<$cpfile>) { if ( /^PLAN=(.*)$/ ) { $plan = $1; last; }}
	close $cpfile;
	return $plan;
}

sub dupefinder { # regex match through backups to properly submit to dupesorter, takes @backups as argument
	my (@backups) = @_;
	foreach (reverse @backups) {
		my $backup = $_;
		if ( /\bbackup-([1][0-2]|[0-9])\.([1-9]|[12][0-9]|[3][01])\.[2][0-9]{3}_(\d{2})-(\d{2})-(\d{2})_([a-z0-9]{1,8})(.tar|tar.gz)?\b/ ) { &dupesorter($6, $backup); }
		elsif ( /\bcpmove-([a-z0-9]{1,8}).tar(.gz)?\b/ or /\b([a-z0-9]{1,8}).tar.gz\b/ ) { &dupesorter($1, $backup); }
	}
	return;
}

sub dupesorter { # sort submitted backups into hashes
	my ($user, $backup) = @_;
	$backups{$backup} = $user;
	if ($seenuser{$user}++) { $dupebackups{$backup} = $user; }
	else { $nondupebackups{$user} = $backup; }
	return;
}

sub duplicateoptionerror {
	my ($option) = @_;
	&printh("Duplicate option '$option' found.  Discarding.\n");
	return;
}

sub existingaccount { # takes $backupuser as argument.  Designed to collect UI info, backup then remove account for restore process
	my ($backupuser) = @_;
	&accountinfo($backupuser);
	&backupacct($backupuser);
	&printh("Killing account '$backupuser' in 5 seconds...\n");
	sleep 5;
	
	# we redefine SIGINT here to keep this script from being interrupted while restore is happening
	local $SIG{'INT'} = 'IGNORE';

	# set original homedir for later use for error checking
	my $homedir = &homedir($backupuser);

	my $logfile = "$logdir/$backupuser-killacct.log";
	&printb("Log file will be stored:\n    at -> $logfile\n");
	my @log = `/usr/bin/yes | $conf{'nice'} $conf{'nicevalue'} $conf{'killacct'} $backupuser 2>&1` or my $killacctdie = 1; # we add to $killacctdie instead of dieing so we can write to the log file
	open my $logfileout, ">>", $logfile or die "Can't write to file '$logfile' [$!]\n";
	foreach (@log) {
		print {$logfileout} $_;
	}
	close $logfileout;
	open my $logfilein, "<", $logfile
		or die "Can't open '$logfile' for reading: $!\n";
	my @logfilein = <$logfilein>;
	close $logfilein;

	my $killacctmatch;
	foreach(@logfilein) { $killacctmatch++ and last if /^$backupuser account removed/; }

	if ($killacctmatch == 1) { print "\n"; &prints("Killacct process completed without obvious error for '$backupuser'.\n\n"); }
	else {
		&printh("Problem killing account $backupuser!  Please review the log file:\n    at -> $logfile\n\nFor details.\n");
		push @killacctfailed, $backupuser;
		&printb("Finishing up...");
		&restorecomplete;
	}

	if (defined($killacctdie)) { if ($killacctdie == 1) { &printe("Problem killing account $backupuser! Please review the log for details.\n"); } }
	my $cpuserfile = "/var/cpanel/users/$backupuser";
	&printe("Problem removing account!\n", color('red'), "The homedir, $homedir, or the cPanel user file, $cpuserfile, is still present. Please review $backupuser-killacct.log; once the homedir and cPanel user file are gone, you can safely re-run this restore.\n") if (( -s $homedir ) || ( -s $cpuserfile ));
	
	local $SIG{'INT'} = \&catchsigint;

	&printh("Sleeping for 60 seconds prior to restoring due to cPanel bug.\n");
	sleep 60;
	print "\n";
	return;
}

sub getuidofuser {
	my ($user) = @_;
	my $uidline;
	open my $etcpasswd, "<", "/etc/passwd" or die "Can't open file /etc/passwd at $!";
	my @eplines = <$etcpasswd>;
	close $etcpasswd;
	foreach (@eplines) {
		if ( /^$user:/ ) { 
			my @uidline = split(/:/, $_);
			$uidline = $uidline[3];
			last;
		}
	}
	if (!$uidline) { &printe("Can't get uid for $user from /etc/passwd\n"); }
	return $uidline;
}

sub help { return "Usage: $conf{'scriptname'} (--reseller=username|--shared=username --single=/path/to/backupfile)  [--nice=(-20 to 19)] [--backuplist=filename] [--listbackups | --backupall] [--help] [--version]\n"; } # small help

sub helpcheck {
	my (@options) = @_;
	if ( grep { /^(--help|-h)$/ } @options ) { # if --help is anywhere in the arguments, print help instead, then exit normally
		&prints(&help);
		print &helpdetails;
		exit 0;		
	}
}

sub helpdetails { # big help?
		return q{
* --shared=user --single=/path/to/backupfile
* --reseller=reselleruser | must be a reseller; checks /var/cpanel/resellers
* --nice=(-20 to 19) | takes a value from -20 to 19.  19 is the lowest
	priority, while -20 is the highest.  15 is the default.
* --listbackups | lists all available, compatible backups in reseller's
	homedir
* --backupall | backups up all resold accounts owned by reseller, places
	them in a new, dated directory in reseller's homedir
* --backuplist=filename | specify a filename that contains a list
	of backups; can be just a filename, which will cause this script
	to look in the reseller's homedir for the file, or full path and
	filename. If either --listbackups or --backupall is present, must
	precede that argument.
* --version -v | show version
* --help -h | show this help

What this script does:

This script is designed to make the restoration of multiple backups provided by a reseller easier; this is not an interface to restoring backups from NAS.


This script automates the restore process as outlined on the GatorWiki at:
    -> https://gatorwiki.hostgator.com/Admin/CPanelBackupsAndRestores#Restoring_Backups


For full documentation of rrbackups, please see the GatorWiki article at:
    -> https://gatorwiki.hostgator.com/Admin/RrBackups

}
}

sub homedir {
	my ($user) = @_;
	my $homedir = File::HomeDir->users_home($user);
	return $homedir;
}

# takes username as argument - checks if IP changed on an account that was removed then restored,
# if so, changes back, then reloads bind, rebuild's Apache httpd.conf, and gracefully restarts
# Apache
sub ipchangecheck { 
	my ($user) = @_;
	$backupuser = $user;
	my $newip = &cpuserip($user);
	if (defined($originalip)) {
		&printb("Checking if IP changed from $originalip...");
		if ($originalip ne $newip) {
			print "\n";
			&printh("IP changed for pre-existing account!\n");
			my $chgacctip = '/root/bin/chgacctip';
			if ( -s $chgacctip ) {
				chmod 0700, $chgacctip if ( ! -X $chgacctip );
				&printb("Changing IP from $newip to $originalip\n"); 
				my $logfile = "chgacctip.log";
				&lognotice($logfile, $user);
				&logtofile("$chgacctip $user $originalip", $logfile);
				&printb("Reloading BIND\n"); &logtofile('/usr/sbin/rndc reload 2>&1', 'rndc-reload.log');
				&printb("Rebuilding Apache configuration\n"); &logtofile('/scripts/rebuildhttpdconf 2>&1', 'rebuild_httpd.conf.log');
				&printb("Gracefully restarting Apache\n"); &logtofile('/etc/init.d/httpd graceful 2>&1', 'httpd_graceful.log');
				&prints("IP change process complete for user $user\n");
			}
			else { 
				my $urlofchgacctip = 'http://git.hgfix.net/chgacctip/chgacctip';
				
				&printh("chgacctip not available!  Fetching and installing from $urlofchgacctip ...\n");
				getstore $urlofchgacctip, $chgacctip || die "Unable to fetch/write $urlofchgacctip to $chgacctip at $!";
				chmod 0700, $chgacctip || die "Unable to update permissions for $chgacctip at $!";
				# call ipchangecheck after chgacctip grabbed and installed
				&ipchangecheck($user);
			}
		}
		else { print color('bold white'), "OK\n", color('reset'); }
	}
	else { &printh("Account didn't exist prior to restore, skipping IP check\n"); }
	return;
}

sub largewarning { &printh("This process may take a while if the account/backup is large.\n"); return; }

sub listbackups {
	if (defined($backuplistfile)) {
		if (grep { !/^\/.*/ } $backuplistfile) { $backuplistfile = &homedir($rrbackup{'reselleruser'}) . "/$backuplistfile"; }
		if ( -T $backuplistfile ) { &printb("Using: $backuplistfile as list of backups.\n"); }
		else { &printe("Error!  $backuplistfile is not a valid text file or doesn't exist!  Exiting.\n"); }
		print "\n";
		&printb("Showing all backups listed in the file: ", color('bold white'), "$backuplistfile\n\n");
		open my $backuplistfilein, "<", $backuplistfile || die "Can't open file $backuplistfile!";
		while (<$backuplistfilein>) {
			chomp(my $line = $_);
			print "\t$line\n";
		}
		close $backuplistfilein;
		print "\n";
	}
	else {
		&printb("The available backups from ", &homedir($rrbackup{'reselleruser'}), " are as follows:\n\n");
		&dupefinder(&backups);
		# empty the @backups for population by %nondupebackups hash
		@backups = ();
		die "\%nondupebackups is empty at $!" if (!%nondupebackups);
			my @availbackups;
			while ( my ($user, $backup) = each %nondupebackups ) {
				push @backups, $backup;
				push(@availbackups, "    $user => $backup\n");
			}
			foreach (sort @availbackups) {
				print;
			}
		if (%dupebackups) {
			print "\n";
			&printb("The extra backups, per user, are as follows: \n\n");
			while (my ($backup, $user) = each %dupebackups) {
				print "    $user => $backup\n";
			}
		}
		print "\n";
	}
	return;
}

# takes $logfile, $logmsg, and $backupuser as arguments

sub lognotice {
	my ($logfile, $backupuser, @logmsg) = @_;
	die "No log file defined at $!" if (!defined($logfile));
	@logmsg = ("Log file will be stored:\n    at -> ", color('yellow'), "$logdir/$backupuser-$logfile\n") if (!@logmsg);
	&printb(@logmsg);
	return;
}

sub logtofile {
	my ($command, $logname) = @_;
	$logfile = "$logdir/$backupuser-$logname";
	my $writetype = ">>";
	my @log = `$command`;
	open my $logfileout, $writetype, $logfile || &printe("Can't write to log file $logfile! Exiting\n");
	foreach (@log) {
		print {$logfileout} $_;
	}
	close $logfileout;
	return;
}

sub mydotcnfpass {
	open my $dotmycnf, "<", "/root/.my.cnf" or die "Can't open /root/.my.cnf at $!";
	my $mysqlpass;
	while (<$dotmycnf>) {
		if ($_ =~ /^pass="(.*)"$/) { $mysqlpass = $1; }
	}
	close $dotmycnf;
	return $mysqlpass;
}

sub mysqldbrepair { # takes username as argument
	my ($user) = @_;
	&printb("Repairing and optimizing all databases for user '$user'\n");
	chomp(my @dbs = `mysql -e "show databases LIKE '${user}_%'"`);
	shift(@dbs); # remove header for MySQL results
	if (@dbs) {
		my $logfile = "databases.log";
		&lognotice($logfile, $user);
		print "    repairing:  ";
		print "...$_" and &logtofile("$conf{'nice'} $conf{'nicevalue'} /usr/bin/mysqlcheck -or $_", $logfile) foreach(@dbs);
		print "\n\n";
		&prints("Repair/optimize finished.  Check above for errors.\n");
	}
	else { &printh("No databases found!  Skipping.\n"); }
	return;
}

sub mysqlsucheck { # thanks to scriptninja.org/checksql! made some minor code improvements, too
	&printb("Checking for MySQL users with super privileges...\n");
	chomp(my $hostname=hostname);
	my $dbh = DBI->connect("DBI:mysql:database=mysql;host=localhost","root",&mydotcnfpass) || &printe("ERROR: couldn't connect to MySQL! Exiting.\n");
	my $querystring = qq{select * from user where (Select_priv="Y" OR Insert_priv="Y" OR Update_priv="Y" OR Delete_priv="Y" OR Create_priv="Y" OR Drop_priv="Y" OR Reload_priv="Y" OR Shutdown_priv="Y" OR Process_priv="Y" OR File_priv="Y" OR Grant_priv="Y" OR References_priv="Y" OR Index_priv="Y" OR Alter_priv="Y" OR Show_db_priv="Y" OR Super_priv="Y" OR Create_tmp_table_priv="Y" OR Lock_tables_priv="Y" OR Execute_priv="Y" OR Repl_slave_priv="Y" OR Repl_client_priv="Y" OR Create_view_priv="Y" OR Show_view_priv="Y" OR Create_routine_priv="Y" OR Alter_routine_priv="Y" OR Create_user_priv="Y" OR Event_priv="Y" OR Trigger_priv="Y") AND User NOT IN ("root","cpldap","roundcube","cphulkd")};
	my $query = $dbh->prepare($querystring);
	$query->execute();
	while ( my @row = $query->fetchrow_array) {
	        push (@sumysqlusers, "$hostname: $row[1]\n");
	}
	if (@sumysqlusers) {
		&printh("The following MySQL users were found with super privileges:\n\n");
		while ( my $sumysqluser = @sumysqlusers ) { &printh($sumysqluser); }
		&printh("It's important that you resolve these before continuing!");
		exit 1 if (&continuequery == 1);
	}
	return;
}

sub options {
	my (@options) = @_;
	# unpack @options and grab first scalar variable
	my ($reselleroruser) = @options;
	# expect first scalar variable to be --reseller
	if ( (defined($reselleroruser)) && ($reselleroruser =~ /^--reseller=([a-z0-9]{1,8})$/ )) {
		$rrbackup{'reselleruser'} = $1;
		if ( &resellercheck($rrbackup{'reselleruser'}) == 1 ) {
			&resellererror;
		}
		elsif ( &resellercheck($rrbackup{'reselleruser'}) == 0 ) { 
			&printb("Reseller specified: $rrbackup{'reselleruser'}\n");
			
		}
		my %delh;
		$delh{$reselleroruser} = ();
		@options = grep {! exists $delh{$_} } @options;
	}
	elsif ( (defined($reselleroruser)) && ($reselleroruser =~ /^--(shared|user)=([a-z0-9]{1,8})$/ )) {
		$rrbackup{'shareduser'} = $2;
		$backupuser = $2;
		my %delh;
		$delh{$reselleroruser} = ();
		@options = grep {! exists $delh{$_} } @options;
		&shareduser($rrbackup{'shareduser'}, $reselleroruser, @options);
	}
	else {
		# First entry not --reseller=resellername?  That's a stabbin'!
		my @defaultreseller = split(/\//, &Cwd::cwd());
		my $defaultreseller = $defaultreseller[2];
		if (@defaultreseller > 2) {
			my $cwdhomedir = join('/', '',$defaultreseller[1],$defaultreseller[2]);
			$defaultreseller = '' if ((!defined($defaultreseller)) || ($cwdhomedir ne &homedir($defaultreseller)));
		}
		else { $defaultreseller = ''; }
		&printh("No reseller specified. Please enter the reseller.\n\n");
		print "    reseller [$defaultreseller] : ";
		$rrbackup{'reselleruser'} = <>;
		chomp($rrbackup{'reselleruser'});
		if ($rrbackup{'reselleruser'} =~ /^$/) { $rrbackup{'reselleruser'} = $defaultreseller; }
		if ( &resellercheck($rrbackup{'reselleruser'}) == 1 ) {
			&resellererror;
		}
		elsif ( &resellercheck($rrbackup{'reselleruser'}) == 0 ) {
			print "\n";
			&printb("Reseller specified: $rrbackup{'reselleruser'}\n");
			print "\n";
		}
	}

	# initialize %seenoptions for identifying duplicate option and discarding
	my %seenoptions;

	# iterate through @options until exhausted, then continue to &rrbackups
	while (defined(my $option = shift @options)) {
		if ( $option =~ /^(--nocolor|-nc)$/ ) {
			&printb("Color disabled with: $option\n");
		}
		elsif ( $option =~ /^--nice=([-](20|1?\d)|1?\d)$/ ) {
			$option = "--nice";
			if ($seenoptions{$option}++) { 
				&duplicateoptionerror($option);
			}
			else { 
				$conf{'nicevalue'} = "$1";
				&printb("Setting niceness to: $conf{'nicevalue'}\n");
			}			
		}
		# file name with one backup file per line
		elsif ( $option =~ /^--backuplist=(\S+)$/ ) { 
			$backuplistfile = $1;
			$option = "--backuplist";
			if ($seenoptions{$option}++) {
				# we want to error out on this to avoid a bug where the backuplist can't be read
				&printe("Two or more --backuplist options present!  Please remove them and try again.\n");
			}
			else {
				if (grep { !/^\/.*/ } $backuplistfile) { $backuplistfile = &Cwd::cwd() . "/$backuplistfile"; }
				if ( -T $backuplistfile ) { &printb("Using: $backuplistfile as list of backups.\n"); }
				else { &printe("Error!  $backuplistfile is not a valid text file or doesn't exist!  Exiting.\n"); }
			}				
		}		
		elsif ( $option =~ /^--listbackups$/ ) {
	# if --backuplist is present, we want it to process FIRST before --listbackups, so push
	# --listbackups to the end of @options
			if (!grep { /^--backuplist=(\S+)$/ } @options) {
				&listbackups;
				exit 0;
			}
		}
		elsif ( $option =~ /^--backupall$/ ) {
			$option = "--backupall";
			if ($seenoptions{$option}++) { 
				&duplicateoptionerror($option);
			}
			else {
				&printh("--backupall passed.  All other arguments ignored.\n");
				&backupall($rrbackup{'reselleruser'});
				exit 0;
			}
		}
		elsif ( $option =~ /^--keepquotas?$/ ) { 
			$conf{'keepquotas'} = 'yes';
			&printb("Option specified: --keepquotas\n");
			&printh("Quotas will not be changed if this is a reseller.\n");
		}
		else { 
			&printe("One or more invalid options specified!  Please try again.\n");
		}
	}
	return $rrbackup{'reselleruser'};
}

# takes $backupuser and $logfile as two arguments
sub perms {
	my ($backupuser, $logfile) = @_;
	my $homedir = &homedir($backupuser);
	die "/root/bin/perms empty or does not exist at $!" if ( ! -s "/root/bin/perms" );
	&printb("Repairing permissions using /root/bin/perms\n");
	&lognotice($logfile, $backupuser);
	&logtofile("cd $homedir && $conf{'nice'} $conf{'nicevalue'} /root/bin/perms", $logfile);
	return;
}

sub planchangecheck {
	my ($user) = @_;
	$backupuser = $user;
	if (defined($originalplan)) {
		&printb("Checking if plan changed from '$originalplan'...");
		my $newplan = &cpuserplan($user);
		if ($originalplan ne $newplan) {
			print "\n";
			&printh("Plan changed for pre-existing account!\n");
			open my $cpfilein, "<", "/var/cpanel/users/$user" || &printe("Unable to open /var/cpanel/users/$user!\n");
			my @cpfilelines = <$cpfilein>;
			close $cpfilein;

			&printb("Changing plan from '$newplan' to '$originalplan'\n");
			open my $cpfileout, ">", "/var/cpanel/users/$user" || &printe("Unable to open /var/cpanel/users/$user for writing!\n");
			foreach (@cpfilelines) {
				if ( /^PLAN=(.*)/ ) { print $cpfileout "PLAN=$originalplan\n"; }
				else { print $cpfileout $_; }
			}
			close $cpfileout;
		}
		else { print color('bold white'), "OK\n", color('reset'); }
	}
	else { &printh("Account didn't existing prior to restore, skipping plan check\n"); }
	return;
}

sub postrestorecheck { # takes username as argument, mainly checks if OWNER is different than reselleruser and adjusts
	my ($user) = @_;
	&mysqlsucheck; # check for superuser privileges in MySQL restored from backup
	$owner = &checkownerofcpaneluser($user);
	&printe("Can't continue; \$owner is empty!  This is likely because the restorepkg script failed.  Please review the logs in:\n    $logdir\n") if (!defined($owner));

	if ($rrbackup{'shareduser'}) {
		$rrbackup{'reselleruser'} = 'root';
		if (&checkownerofcpaneluser($user) ne $rrbackup{'reselleruser'}) {
			&printh("Owner of restored shared user is '$owner', different than $rrbackup{'reselleruser'}.\n");
			&printh("Changing owner to: $rrbackup{'reselleruser'}\n");
		}
	}
	elsif ($rrbackup{'reselleruser'}) {
		if ($owner ne $rrbackup{'reselleruser'}) {
			&printh("Owner of restored user is '$owner', different than the reseller '$rrbackup{'reselleruser'}'\n");
			&printh("Changing owner to: $rrbackup{'reselleruser'}\n");
		}
	}

	open my $cpfilein, "<", "/var/cpanel/users/$backupuser" or &printe("Unable to open cPanel user file!\n");
	my @lines = <$cpfilein>;
	close $cpfilein;
	open my $cpfileout, ">", "/var/cpanel/users/$backupuser" or &printe("Unable to open cPanel user file!\n");
	foreach (@lines) {
		s/^OWNER=.*/OWNER=$rrbackup{'reselleruser'}/;
		print {$cpfileout} $_;
	}

	close $cpfileout;
	my ($bwlimit, $dulimit);
	# we only want to reset to ~1 TB du/unlimited bandwidth on our gator(\d+) servers
	print "\n";
	if ($rrbackup{'shareduser'}) {
		&printh("Account restored is a shared user");
		if (hostname =~ /^gator(\d+).hostgator.com$/) {
			print " and on a Hostgator shared server.\n    Setting bandwidth unlimited and disk usage limit to 999999 MB\n";
			$bwlimit = 0;
			$dulimit = "999999M";
			&checkresetdiskquotas($bwlimit, $dulimit);
		}
		else {
			print " but not on a Hostgator shared server.  Skipping bandwidth/disk usage limit resets.\n";
			return;
		}
	}
	else {
		if ($conf{'keepquotas'} eq 'yes') {
			&printh("Account restored is a resold user, but disk/bandwidth quotas will not be reset due to the --keepquotas flag.\n");
		}
		else {
			&printh("Account restored is a resold user.  Setting bandwidth to 100MB and disk usage limit to 100MB\n");
			$bwlimit = 100;
			$dulimit = "100M";
			&checkresetbwdiskquotas($bwlimit, $dulimit);
		}
	}
	print "\n";
	&prints("Finished with post restore checks/adjustments.  Please check for errors.\n");
	return;
}

sub prerunchecks { # stuff that needs to receive the 'OK' before even starting the main program
	my @result;
	my $cpaneldir = '/usr/local/cpanel';
	if (( ! -s $cpaneldir ) && ( ! -d $cpaneldir )) { push @result, 1 } 
	elsif (( $ENV{"TERM"} ne "screen" )) { push @result, 2 }
	if ( grep { /^1$/ } @result ) {
		&printe("$cpaneldir does not exist or is empty! This script is only for cPanel servers.  Exiting.\n");
	}
	elsif ( grep { /^2$/ } @result ) {
		&printh("You're not running this in screen, which is strongly recommended.\n");
		exit 0 if &continuequery == '0';
		print "\n";
	}
	return;
}

# standard message
sub printb { my (@print) = @_;	print color('bold blue'), @print, color('reset'); return; }

# exit (with error status 1)
sub printe { my (@print) = @_; print STDERR color('bold red'), @print, color('reset'); exit 1; }

# warning!
sub printh { my (@print) = @_; print color('bold green'), @print, color('reset'); return; }

# question?
sub printq { my (@print) = @_; print color('bold yellow'), @print, color('reset'); return; }

# finished message template
sub prints { my (@print) = @_; print color('bold white'), @print, color('reset'); return; }

sub resellercheck {
	# check if &homedir for $rrbackup{'reselleruser'} exists, if the cPanel user file for $rrbackup{'reselleruser'} is not empty, and checks that
	# the $rrbackup{'reselleruser'} is actually is a reseller in /var/cpanel/resellers - checks are separated into single conditions
	# so that &homedir($rrbackup{'reselleruser'}) doesn't return a blank value/return a perl warning if the user doesn't even exist
	if (! -s "/var/cpanel/users/$rrbackup{'reselleruser'}") { return 1; }
	elsif (! &resellercheckfile($rrbackup{'reselleruser'})) { return 1; }
	elsif (! -d &homedir($rrbackup{'reselleruser'})) { return 1; }
	else {
		# we need to do $backupdir/$logdir stuff here! - 11/04/11
		my $basedir = "/home/hgtransfers";
		mkdir $basedir if (! -d $basedir);
		my $rrdir = "/home/hgtransfers/rrbackups";
		mkdir $rrdir if (! -d $rrdir);
		$backupdir = "$rrdir/$rrbackup{'reselleruser'}-$conf{'date'}";
		mkdir $backupdir if (! -d $backupdir);
		$logdir = "$backupdir/logs";
		mkdir $logdir if (! -d $logdir);
		# return 0 means he is a reseller
		return 0;
	}
}

sub resellercheckfile {
	my ($user) = @_;
	open my $cpanelresellersfile, '<', '/var/cpanel/resellers' or &printe("Can't open resellers file!");
	while (my $line = <$cpanelresellersfile>) { if ( $line =~ /^$user:(.*)+$/ ) { return 1; } }
	close $cpanelresellersfile;
	return 0;
}

sub resellererror { &printe("Reseller '$rrbackup{'reselleruser'}' invalid! The reseller's homedir does not exist, their cPanel user file is empty or not present, and/or they are not a valid reseller in WHM.  Please check and try again.\n"); return; }

sub restorebackup { # takes a full path as argument
	($backup) = @_;
	my @backup = split(/\//, $backup);
	$_ = $backup[-1]; # returns backup file with NO path
	if ( /^backup-([1][0-2]|[0-9])\.([1-9]|[12][0-9]|[3][01])\.[2][0-9]{3}_(\d{2})-(\d{2})-(\d{2})_([a-z0-9]{1,8})(.tar|tar.gz)?$/ ) { $backupuser = $6; } # should match 3 backups - 10/26/11
	elsif ( /^cpmove-([a-z0-9]{1,8}).tar(.gz)?$/ ) { $backupuser = $1; }
	elsif ( /([a-z0-9]{1,8}).tar.gz$/ ) { $backupuser = $1; }
	else { &printh("Invalid backup file, $backup.  Skipping to next backup.\n"); }
	my $cpfile = "/var/cpanel/users/$backupuser";

	# some checks just so we don't break stuff
	&printe("cPanel user file for '$backupuser' is empty! Broken account?  Exiting.\n") if ( -z $cpfile );

	my $owner;
	$owner = $rrbackup{'reselleruser'} if defined $rrbackup{'reselleruser'};
	$owner = 'root' if defined $rrbackup{'shareduser'};

	if ( $backupuser eq $owner ) {
		&printh("The backupuser, $backupuser, is the same as the reseller specified!  Are you crazy? Skipping this backup.\n");
		push @restoresfailed, $backup;
	}
	else {
		my $cpmovefile = "/home/cpmove-$backupuser.tar.gz";
		my $newnameforcpmovefile = "$cpmovefile.renamed-by-rrbackups-for-$backupuser-$conf{'date'}";
		if ( -f $cpmovefile ) {
			&printh("A cpmove file for $backupuser is present at $cpmovefile\n    Renaming to $newnameforcpmovefile keep cPanel from restoring it...\n");
			&move($cpmovefile, $newnameforcpmovefile) || die "Can't move $cpmovefile to $newnameforcpmovefile at $!";
		}
		print "\n";	
		&printb("Proceeding with restore...\n\n");
		&printh("Now restoring:\n    ", color('bold white'), "$backupuser -> $backup\n\n");
		# prevent a backup from being restored where the --shared=user doesn't match the user for the backup
		if ($rrbackup{'shareduser'}) {
			# do some sanity checks here to prevent problems
			&printe("User contained in backup, $backupuser, does not match specified --shared user, $rrbackup{'shareduser'}! Exiting.\n") if $rrbackup{'shareduser'} ne $backupuser;
		}

		&printe("User aborted restore for backup $backup for user $backupuser! Exiting.\n") if (&continuequery == 0);
	
		print "\n";
		if ( ( ! -e $cpfile ) || ( -z $cpfile ) ) {
			&printe("Big problem:  User '$backupuser' has homedir at ", &homedir($backupuser), " but the cPanel user file, $cpfile, is empty or missing.  Might want to look at it.\n") if (defined(&homedir($backupuser)));
			&printe("Big problem:  Found directory, /home/$backupuser, which may conflict with the backup you're trying to restore.  This might be a partial account where the cPanel user file is missing/empty, or it may just be an empty directory.\n\n    Unable to continue.\n\n") if (-s "/home/$backupuser");
		}

		# check if cPanel user exists, if so, prompt for backup/removal
		if ( -s $cpfile ) {
			&printh("User '$backupuser' exists!\n");
			&printh("You have the option of collecting account information, backing up, removing, then restoring.\n\n");
			if ( &continuequery == 1 ) { # we need to do something here, sir - 10/24/11
				print "\n";
				&existingaccount($backupuser); # collect UI info, uses &restorebackupnow, removes/starts restore - 10/26/11
				#&existingdomain(); # future - check backup file if contains a domain that exists on server - 11/01/11
				&restorebackupnow($backup);
				if ( $rrbackup{'uiused'} eq "bash") { if (unlink($conf{'newui'}) == 0) { &printh("File $conf{'newui'} failed to be deleted.\n"); } } # not a show stopper, so just give a warning
			}
			else {
				push @restoresfailed, $backup;
				&printh("Skipping '$backupuser' to next user...\n");
			}
		}
		# if pre-checks pass, then continue with restore
		else {
			&restorebackupnow($backup);
		}
	}
	return;
}

sub restorebackupnow {
	my ($localbackup) = @_;
	&printb("Now restoring backup:\n    at -> ", color('yellow'), "$localbackup ...\n");
	sleep 1;
	my $logfile = "$logdir/$backupuser-restorepkg.log";
	&printb("Log file will be stored:\n    at -> ", color ('yellow'), "$logfile\n");
	print "\n"; &largewarning;
	
	# we redefine SIGINT here to keep this script from being interrupted while restore is happening
	local $SIG{'INT'} = 'IGNORE';

	my @log = `$conf{'nice'} $conf{'nicevalue'} $conf{'restorepkg'} $localbackup 2>&1` || &printe("Error encountered during restore!  Please review the logs at: ", color('yellow'), "$logdir");
	open my $logfileout, ">>", $logfile || &printe("Can't write to log file! Exiting\n");
	foreach (@log) { print {$logfileout} $_; }
	close $logfileout;

	open my $logfilein, "<", $logfile
		or die "Can't open log file $logfile for reading: $!";
	my @logfilein = <$logfilein>;
	my $restorecompletematch;
	foreach (@logfilein) { if (/^Account Restore Complete/) { $restorecompletematch++; last; } }
	close $logfilein;

	if ($restorecompletematch == 1) { print "\n"; &printb("Restorepkg found no issues restoring and was able to successfully complete the restore.\n\n"); }
	else {	&printe("Restorepkg issue:  it was unable to find the backup to use.\n    If you're using --backuplist, you most likely neglected to add the full path for the specified backup, '$localbackup'\n    Please check the log file:\n    at -> ", color('yellow'), "$logfile", color('red'), "\n\n    For further details."); }

	sleep 1;
	@restorescompleted = (@restorescompleted, $localbackup);
	&prints("Restore of $localbackup finished for user '$backupuser'.\n\n");
	# restore SIGINT default
	local $SIG{'INT'} = \&catchsigint;

	&printb("Continuing with post-restore checks...\n");
	&postrestorecheck($backupuser);
	print "\n\n";
	&printb("All most done...\n\n\n"); sleep 3;
	&printb("Running preexistent account checks:\n\n\n");

	&ipchangecheck($backupuser);
	print "\n";
	&planchangecheck($backupuser);
	print "\n";

	&printb("Updating user domains to reflect changes\n"); 
	&logtofile("$conf{'nice'} $conf{'nicevalue'} /scripts/updateuserdomains 2>&1", "$backupuser-updateuserdomains.log");
	print "\n";
	&prints("Preexisting account checks done.\n\n\n");

	&printb("Here's the new account info:\n\n");
	&accountinfo($backupuser);

	print "\n";
	&prints("Entire restore process complete for user '$backupuser'.\n");
	&printe("Restore aborted by user! Quitting.\n") if ( &continuequery == 0 );
	print "\n";
	&printb("Going to next backup...\n\n");
	return;
}

sub restorecomplete {
	&printb("+-++-++-++-++-++-++-+ +-++-++-++-++-++-++-++-+\n");
	&printb("|R||E||S||T||O||R||E| |C||O||M||P||L||E||T||E|\n");
	&printb("+-++-++-++-++-++-++-+ +-++-++-++-++-++-++-++-+\n\n\n");

	my $finishedbanner;
	$finishedbanner = "Restore finished for user '$rrbackup{'shareduser'}'.\n" if defined $rrbackup{'shareduser'};
	$finishedbanner = "Restores finished for reseller '$rrbackup{'reselleruser'}'.\n" if ((defined $rrbackup{'reselleruser'}) && (!defined $rrbackup{'shareduser'}));
	&prints($finishedbanner);
	print "\n";

	&printb("Successful restores: \n");
	if (@restorescompleted > 0 ) { 
		foreach (@restorescompleted) { print "    $_\n"; }
	}
	else { &printh("No backups were restored\n"); }
	print "\n";

	&printb("Failed restores:    ");
	if (@restoresfailed > 0 ) {
		print "\n";
		foreach (@restoresfailed) { print "    $_\n"; }
	}
	else { &printh("No restores failed\n"); }
	print "\n";

	if (!defined($backuplistfile)) {
		&printb("Extra, unused backups per user: \n");
		if (%dupebackups) {
			while ( my ($backup, $user) = each %dupebackups ) { print "    User: $user => $backup\n"; }
		}
		else { &printh("No duplicate backups\n"); }
		print "\n";
	}

	&printh("The following accounts failed to be killed: \n\n");
	if (@killacctfailed) { print "    $_\n" foreach @killacctfailed; print "\n"; }
	else { print"    -- no accounts --\n"; }
		

	if (@sumysqlusers > 0 ) {
		&printb("The following MySQL users were found with super privileges:");
		foreach (@sumysqlusers) { print "    $_\n"; }
	}
	print "\n";

	&printb("Log files can be found at:\n    ", color('yellow'), "$logdir\n\n"); 
	&printb("Any pre-restore backups created can be found at:\n    ", color('yellow'), "$backupdir/\n");

	if (@restorescompleted > 0) { 
		print "\n";
		if ($rrbackup{'shareduser'}) {
			&printb("Originally provided backup for '$backupuser' is available at:\n    ", color('yellow'), "$backup\n\n");
			&printb("Restore finished for '$backupuser'.\n");
			# no need to print this if the account didn't originally exist
			print "Please be sure to change their plan to the one specified in billing.\n\n" if ((!defined($originalip)) || (!defined($originalplan)));
		}
		else
			{ &printh("Be sure to inform client the package and/or bandwidth/quota for their restored users may need to be reset to their preference.\n");
			&prints("You can also change the package for an account if the client has instructed you what package is intended per account.\n\n"); 
		}
	}
	else { print "\n"; }
	return;
}

sub rrbackups {
	($rrbackup{'reselleruser'}) = @_;
	&printe("Reseller not defined.  Use: --reseller=username and try again.\n") if (!defined($rrbackup{'reselleruser'}));
	if ( &resellercheck($rrbackup{'reselleruser'}) == 0 ) {
		print "\n";
		&printb("Here are the backups I will attempt to restore for reseller '$rrbackup{'reselleruser'}': \n\n");
		if (($backuplistfile) && (-T $backuplistfile)) {
			open my $backuplistfilein, "<", $backuplistfile || &printe("Can't open file $backuplistfile!");
			@backups = (); # make sure @backups is empty... should be, but doesn't hurt to do this
			while (<$backuplistfilein>) {
				chomp(my $line = $_);
				push @backups, $line;
			}
			close $backuplistfilein;
		}
		else {
			&backups($rrbackup{'reselleruser'});
			if(%nondupebackups) {
				@backups = (); # empty the @backups for population by %nondupebackups hash
				while ( my ($user, $backup) = each %nondupebackups ) {
					push @backups, $backup;
				}
			}
			else { # simple check to make sure we're populating %nondupebackups
				&printe("\%nondupebackups is empty! Exiting.\n");
			}
		}
		if (@backups > 0) {
			foreach (@backups) { print "    $_\n"; }
			print "\n";
			&printe("Script must be run as root to restore!  Exiting.\n") if $> != 0;
			if ( &continuequery == 1 ) {
				foreach (@backups) {
					if ( -s $_ ) { &restorebackup($_); }
					else { &printh("Backup file $_ is missing or invalid!  Skipping to next backup.\n"); }
				}
				&restorecomplete;
			}
			else { exit 0; } # not really needed but including for the hell of it
		}
		else { &printe("No backups found in " . &homedir($rrbackup{'reselleruser'}) . ".  Please check and try again.\n"); }
	}
	return;
}

sub sharedbackuprestorenow {
	($backup) = @_;
	if ( -s $backup ) {
		my @backupfile = split(/\//, $backup);
		my $backupfile = $backupfile[-1];
		# we want to move single backups to a safe location prior to the restore
		my $originalbackuplocation = $backup;
		print "\n";
		&printb("Moving provided backup:\n    $backup to $backupdir/$backupfile ...\n\n");
		if (-f $backup) { &move($backup, "$backupdir/$backupfile") || die("Can't move $backup to $backupdir/$backupdir at $!"); }
		elsif (-d $backup) { &printe("Uh oh:  $backup isn't a file but is instead a directory.  Try again!\n"); }
		$backup = "$backupdir/$backupfile";
		&restorebackup($backup);

		my $backupdestination = &homedir($rrbackup{'shareduser'}) . "/$backupfile";
		print "\n";
		if ( @restorescompleted == 1 ) {
			&printb("Moving provided backup:\n    $backup to $backupdestination...\n\n");
			&move($backup, $backupdestination) || die("Can't move $backup to $backupdestination at $!");
			$backup = $backupdestination;
		}
		elsif ( @restoresfailed == 1 ) {
			&printh("Restore failed, keeping backup at $backup\n");
		}
		# we want to die here if neither of these arrays contain exactly 1 piece of data
		else { die "Failure! Neither \@restorescompleted nor \@restoresfailed is defined at $!"; }
		&restorecomplete;
		exit 0;
	}
	else { &printe("Backup file, $backup, missing or empty!  Exiting.\n"); }
	return;
}

sub sharedcheck {
    ($rrbackup{'shareduser'}) = @_;
	# add hostname checking to make sure it's not used on reseller servers
	&printe("Reseller server detected ! --shared can't be used on reseller servers.  Exiting.\n") if (hostname =~ /^(\S+).websitewelcome.com$/);
	my $basedir = "/home/hgtransfers";
	mkdir $basedir if (! -d $basedir);
	my $rrdir = "/home/hgtransfers/rrbackups";
	mkdir $rrdir if (! -d $rrdir);
	$backupdir = "$rrdir/$rrbackup{'shareduser'}-$conf{'date'}";
	mkdir $backupdir if (! -d $backupdir);
	$logdir = "$backupdir/logs";
	mkdir $logdir if (! -d $logdir);
	return 1;
}

sub sharederror { &printe("cPanel user $rrbackup{'shareduser'}' invalid! The user's homedir does not exist or their cPanel user file is empty or not present.  Please check and try again.\n"); return; }

# we're only looking for one valid option here, for now - --single=backupfile - 11/16/11
sub sharedoptions {
    my (@options) = @_;
    while (defined(my $option = shift @options)) {
		if ( $option =~ /^--single=(\/\S+)$/ ) {
			$backup = "$1";
			&sharedbackuprestorenow($backup);
		}
		elsif ( $option =~ /^--single=\.\.(\S+)$/ ) {
			shift @options;
			$backup = $1;
			my @cwddoubledot = split(/\//, &Cwd::cwd);
			pop @cwddoubledot;
			$backup = join("/", @cwddoubledot) . "$backup";
			&sharedbackuprestorenow($backup);
		}			
		elsif ( $option =~ /^--single=\.(\S+)$/ ) {
			shift @options;
			$backup = &Cwd::cwd . $1;
			&sharedbackuprestorenow($backup);
		}
        elsif ( $option =~ /^--single=(\S+)$/ ) {
			$rrbackup{'reselleruser'} = 'root';
			unless ($1 =~ m#/(.*)#) { $backup = &Cwd::cwd . "/$1"; }
			else { $backup = $1; }
			&sharedbackuprestorenow($backup);
        }
        else {
            &printe("Invalid option, '$option', specified!  Please remove and try again.\n");
        }
    }
	return;
}

sub shareduser {
    ($rrbackup{'shareduser'}) = @_;
	my ( $option, @options) = @_;
    &sharedcheck($rrbackup{'shareduser'});
    &printb("Shared user specified: $rrbackup{'shareduser'}\n");
	shift @options;
    # we need to process @options different, so we're calling a different subroutine here, then exiting
    &sharedoptions(@options);
    exit 0;
}

sub versioncheck {
	my (@options) = @_;
	if ( grep { /^(--version|-v)$/ } @options ) { # if --version or -v anywhere in argument, print that and exit
		&printb("$conf{'scriptname'} $conf{'version'}\n");
		exit 0;		
	}
} # you've reached the end of the road, sir.  Rest ye weary bones by the fire.
