#!/usr/local/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:
# - Add option to backup only select accounts.  Try to reuse -- with it. - 02/16/12
#
#--------------------------------------------------
# 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
# - when using &ticketid(@options) and @options is empty, &ticketid(@options) gives uninitialized value - FIXED - 02/07/12 -- also fixed a bug where ticketid would try to move a non-existent directory when a ticketid is entered (and dies)
# - get pre-restore backups list working as always outputs "No pre-restore backups created" regardless if there are any - 11/04/11 - DONE - 02/07/12
# - save pre-restore and post-restore UI results to log files for later review - DONE - 02/08/12
#-------------------------------------------------- 

#--------------------------------------------------
# Bugs:
# - (none so far)
#-------------------------------------------------- 

#--------------------------------------------------
# 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");
# 
# - debug script as a whole - 10/26/11
#-------------------------------------------------- 

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

#--------------------------------------------------
# accountinfo	--				checks for/runs /root/bin/ui and writes results to file and/or returns to STDOUT
# backupacct	--				runs perms/mysqlcheck on all dbs then backs up a single account
# backupall		--				loops through resold/reseller account list matching $reselleruser in /etc/trueuserowners, runs &backupacct for eac
# backups		--				finds all backups in reseller's homedir and pushes to @backups
# begin			--				calls &versioncheck, &helpcheck, and &prechecks, then runs &options to look through arguments, returns values to &rrbackups main sub
# catchsigint	--				what to call for SIGINT handling
# checkownerofcpaneluser --		called when an account exists or post-restore to check OWNER of user, returns 'invalid' if it isn't <= 8 alphanum 
# checkresetbwdiskquotas --		checks/resets bandwidth/disk quotas, depending if it's a shared or resold account
# continuequery --				prompt yes/no, returns 1/0 respectively (yes is the default for no entry)
# cpuserip		--				returns IP from user's cPanel file
# cpuserplan	--				returns PLAN from user's cPanel file
# dupefinder	--				finds and removes 'duplicates'.  Duplicates are when there's more than 1 backup per user
# dupesorter	--				simple regex match to pre-filter backups first
# duplicateoptionerror --		unused currently, does what it says (called in &options)
# existingaccount --			checks if account exists and asks if you wish to backup, remove, then continue with restore (calls &checkownerofcpaneluser too)
# getuidofuser	--				does what it says, returns it
# help 			--				main, sort help
# helpcheck 	--				check @arguments, passed from @ARGV, for --help|-h, returns &help and &helpdetails and exits if so
# helpdetails	--				extended help
# homedir		--				returns homedir of user
# ipchangecheck --				checks if IP changed (account existed then was backed up, removed, then restored)
# largewarning	--				just a bigger warning
# listbackups	--				returns all backups from @backups, which is populated by &backups or from the file passed with --backuplist=filename
# lognotice		--				prints to STDOUT that output will be logged to path/to/log/file
# logtofile		--				runs the system call using backticks and logs array'd output to file
# longsep		--				just a long ruler/divider
# mydotcnfpass	--				reads /root/.my.cnf and returns info to connect to mysql as root
# mysqldbrepair --				runs mysqlcheck -or on passed database
# mysqlsucheck	--				checks for mysql users with superuser access post-restore
# options		--				loops through all arguments and reacts appropriately
# perms			--				runs /root/bin/perms on account
# planchangecheck --			checks if PLAN changed for user and changes back 
# postkillacct	--				checks to make sure account killed completely/properly
# postrestorecheck --			runs &ipchangecheck, &planchangecheck, &mysqlsucheck, &checkresetbwdiskquotas, and more
# prerunchecks --				checks for cPanel present and checks if running in screen
# printb		--				bold white print sub
# printe		--				prints red and exit 1 ('print error')
# printh		--				prints yellow 'warning'
# printq		--				question print
# prints		--				'finished' print
# resellercheckfile --			makes sure the passed reseller is actually a reseller -- checks /var/cpanel/resellers	
# resellererror --				Throws error, called by &resellercheckfile usually (or by the conditional statement that checks the return value of &resellercheckfile)
# resellerorsharedcheck			Checks if reseller's dir exists, creates directories necessary for this program to backup, log, etc., other checks
# restorebackup	--				pre-restore backups checks then calls &restorebackupnow if necessary
# restorebackupnow --			Actually restores the backup then runs post-restore checks
# restorecomplete --			Prints summary of rrbackups runs
# rrbackups		--				Basically starts the whole program after &begin calls &options
# sharedbackuprestorenow --		Restore subroutine just for shared users
# sharederror	--				Similar to resellererror, but for shared user
# sharedoptions	--				Loops through arguments specific to shared users
# shareduser	--				Preps for restore for shared users
# ticketid		--				Ties in &ticketidcheck and &ticketidprompt
# ticketidcheck	--				Checks to see if passed ticket matches 8 numbers or 3 letters, a dash, and 8 numbers
# ticketidprompt --				prompts for ticketid via STDIN
# versioncheck	--				Checks for --version|-v anywhere in arguments, returns version and exits
#-------------------------------------------------- 


use strict;
use warnings;

use DBI;
use File::Find;
use Sys::Hostname;
use POSIX qw/strftime ceil floor/;
use Term::ANSIColor;
use File::Basename;
use File::HomeDir;
use LWP::Simple;
use Cwd;
use File::Copy;
use Time::HiRes;
use Term::ReadKey;

my ($termwidth) = GetTerminalSize();


my (@backups, @backupscompleted, @restorescompleted,  @restoresfailed, @killacctfailed, @sumysqlusers, @restorefileslistfromcli);
my (%dupebackups, %nondupebackups);

my %conf = (
	version 	=> '1.2.1',
	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 --force --killdns";
$conf{'pkgacct'}	= "perl /scripts/pkgacct --userbackup";
$conf{'restorepkg'}	= "perl /scripts/restorepkg --skipres";

if (defined $ENV{'DIAGNOSTIC'} and $ENV{'DIAGNOSTIC'} == 1) { $conf{'diagnostic'} = 1; }
elsif (defined $ENV{'DIAGNOSTIC'} and $ENV{'DIAGNOSTIC'} == 0) { $conf{'diagnostic'} = 0; }
else { $conf{'diagnostic'} = 0; }

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

END { print STDERR "\n$conf{'scriptname'} finished running in ", time - $^T, " seconds.\n" if ($conf{'diagnostic'} and $conf{'diagnostic'} eq 1); exit; close STDOUT or die "can't close stdout: $!"; }

&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
	my $originalip = &cpuserip($backupuser);
	my $originalplan = &cpuserplan($backupuser);

	
	open my $uifile, "<", $uiscript
		or die "Unable to open $uiscript for reading: $1";
	my @lines = <$uifile>;
	close $uifile;

	my ($ui, $uiresults);

	if (!$rrbackup{'uiused'}) {
		while (my $line = shift @lines) {
			if ( $line =~ /perl/ ) {
				$rrbackup{'uiused'} = $ui = "perl $uiscript";
				last;
			}
			elsif ( $line =~ /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'} = $ui = "bash $conf{'newui'}";
				last;
			}
			else { die "Unable to determine if $uiscript is a Perl or Bash script.  Reinstall and try again.\n [$!]"; }
		}
	}

	$uiresults = `$rrbackup{'uiused'} $backupuser`;

	if ($conf{'diagnostic'} == 1) {
		print colored($uiresults, 'bold white');
		&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"); }
		print "\n";
	}
	my $epoch = time;
	my $logfile = "ui.${epoch}.log";
	my $logfilewithdir = "$rrbackup{'backupdir'}/logs/${backupuser}-$logfile";
	&printb("\nSaving output of UI for user ", color('green'), $backupuser, color('bold white'), "\n");
	&lognotice($logfile, $backupuser);
	open my $myuilogout, '>', $logfilewithdir
		or die "Unable to write to $logfilewithdir: [$!]";
	print $myuilogout $uiresults;
	close $myuilogout;		
	return $originalip, $originalplan;
}

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...
	my $logfile = "$rrbackup{'logdir'}/$backupuser-pkgacct.log";
	
	print "\n";	
	&printb("Backing up account: ", color('bold white'), "$backupuser\n", color('reset'), color('cyan'),"    to -> ", color('yellow'), "$rrbackup{'backupdir'}/...\n");
	&printb("Log file will be stored:\n    at -> ", color('yellow'), "$logfile\n");
	&largewarning;

	my $starttime = [Time::HiRes::gettimeofday()];	

	my @log = `$conf{'nice'} $conf{'nicevalue'} $conf{'pkgacct'} $backupuser $rrbackup{'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 $runtime = ceil(Time::HiRes::tv_interval($starttime));
	my $pkgacctmatch;
	foreach(@logfilein) { if (/^pkgacctfile is: (.*)/) { $pkgacctmatch = $1; last; }}
	if (defined($pkgacctmatch)) { print "\n"; &printb("Pkgacct appears to have successfully completed in $runtime seconds, created backup:\n    at -> ", color('yellow'), "$pkgacctmatch\n\n", color('reset')); } 
	else { &printh("Pkgacct failed!  Please review the logfile:\n    at -> $logfile\n"); }
	&prints("Backup for user '$backupuser' finished.");
	&longsep;
	push(@backupscompleted, $pkgacctmatch);
	print "\n";
	
	local $SIG{'INT'} = \&catchsigint;

	return;
}

sub backupall { 
	($rrbackup{'reselleruser'}) = @_;
	if ( &resellerorsharedcheck('reseller', $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(my $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 colored("$_\n", 'bold white') foreach(sort @backupscompleted);
		print "\n";
		&printb("Log files can be found:\n    at -> $rrbackup{'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 ( &resellerorsharedcheck('reseller', $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 !$rrbackup{'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);
	print color('red'), "\n$conf{'header'}\n\n", color('reset');
	&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");
	my $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, $backupuser) = @_;
	&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", $backupuser);
	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) = @_;
	my %backups;
	$backups{$backup} = $user;
	my %seenuser;
	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) = @_;
	my ($originalip, $originalplan) = &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 = "$rrbackup{'logdir'}/$backupuser-killacct.log";
	&printb("Log file will be stored:\n    at -> ", color('yellow'), $logfile, "\n", color('reset'));
	my $starttime = [Time::HiRes::gettimeofday()];

	my $killacctdie = 0;
	# we add to $killacctdie instead of dieing so we can write to the log file
	my @log = `$conf{'nice'} $conf{'nicevalue'} $conf{'killacct'} $backupuser 2>&1`
		or $killacctdie = 1; 

	&postkillacct($homedir, $starttime, $killacctdie, $backupuser, $logfile, @log);

	return $originalip, $originalplan;
}

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] [--keepquotas] [--nocolor] [--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
* [ticketid] (optional) | can be either the 8-digit ticket ID, or the full format:
	XXX-NNNNNNNN
* --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 --pretend -p | 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.
* --keepquotas | prevent resold account disk/bandwidth quotas from being reset
* --nocolor -nc | turns off color
* --skipexisting | skips existing accounts
* --bakexisting | auto-backs up and kills existing accounts
* --force/-f | use with caution; can be used with --bakexisting or --skipexisting
* -- | any arguments following the double dash will be treated as backups to
	restore
* --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, $originalip) = @_;
	my $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, $backupuser);
				&printb("Reloading BIND\n") and &logtofile('/usr/sbin/rndc reload 2>&1', 'rndc-reload.log', $backupuser);
				&printb("Rebuilding Apache configuration\n") and  &logtofile('/scripts/rebuildhttpdconf 2>&1', 'rebuild_httpd.conf.log', $backupuser);
				&printb("Gracefully restarting Apache\n") and &logtofile('/etc/init.d/httpd graceful 2>&1', 'httpd_graceful.log', $backupuser);
				&prints("IP change process complete for user $user.");
				&longsep;
			}
			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 $rrbackup{'backuplistfile'}) {
		if (grep { !/^\/.*/ } $rrbackup{'backuplistfile'}) { $rrbackup{'backuplistfile'}= &homedir($rrbackup{'reselleruser'}) . "/$rrbackup{'backuplistfile'}"; }
		if ( -T $rrbackup{'backuplistfile'}) { &printb("Using: $rrbackup{'backuplistfile'} as list of backups.\n"); }
		else { &printe("Error!  $rrbackup{'backuplistfile'} is not a valid text file or doesn't exist!  Exiting.\n"); }
		&printb("\nShowing all backups listed in the file: ", color('bold white'), "$rrbackup{'backuplistfile'}\n\n");
		open my $backuplistfilein, "<", $rrbackup{'backuplistfile'} || die "Can't open file $rrbackup{'backuplistfile'}: [$!]";
		while (<$backuplistfilein>) {
			chomp(my $line = $_);
			print "\t$line\n";
		}
		close $backuplistfilein;
		print "\n";
	}
	else {
		&printb("\nThe available backups from ", colored(&homedir($rrbackup{'reselleruser'}), 'bold white'), color('cyan'), " 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");
			}
			print colored("$_", 'bold white') foreach (sort @availbackups);
		if (%dupebackups) {
			print "\n";
			&printb("The extra backups, per user, are as follows: \n\n");
			while (my ($backup, $user) = each %dupebackups) {
				print colored("    $user => $backup\n", 'yellow');
			}
		}
		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'), "$rrbackup{'logdir'}/$backupuser-$logfile\n") if (!@logmsg);
	&printb(@logmsg);
	return;
}

sub logtofile {
	my ($command, $logname, $backupuser) = @_;
	my $logfile = "$rrbackup{'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 longsep {
	unless (defined $ENV{'ANSI_COLORS_DISABLED'} and $ENV{'ANSI_COLORS_DISABLED'} eq '1') {
		print "\n", color('bold white');
		for (my $i=1; $i <= $termwidth; $i++) { print "-"; }
		print "\n", color('reset');
		return 0;
	}
	return 1;
}

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 colored("    repairing:  ", 'bold white');
		print colored("...$_", 'red') and &logtofile("$conf{'nice'} $conf{'nicevalue'} /usr/bin/mysqlcheck -or $_", $logfile, $user) foreach @dbs;
		print "\n\n";
		&prints("Repair/optimize finished.  Check above for errors.");
		&longsep;
	}
	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 ( &resellerorsharedcheck('reseller', $rrbackup{'reselleruser'}) == 1 ) {
			&resellererror;
		}
		elsif ( &resellerorsharedcheck('reseller', $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;
		my $backupuser = $2;
		my %delh;
		$delh{$reselleroruser} = ();
		@options = grep {! exists $delh{$_} } @options;
		@options = &ticketid(@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 colored("    reseller [$defaultreseller] : ", 'bold white');
		$rrbackup{'reselleruser'} = <>;
		chomp($rrbackup{'reselleruser'});
		if ($rrbackup{'reselleruser'} =~ /^$/) { $rrbackup{'reselleruser'} = $defaultreseller; }
		if ( &resellerorsharedcheck('reseller', $rrbackup{'reselleruser'}) == 1 ) {
			&resellererror;
		}
		elsif ( &resellerorsharedcheck('reseller', $rrbackup{'reselleruser'}) == 0 ) {
			print "\n";
			&printb("Reseller specified: $rrbackup{'reselleruser'}\n");
			print "\n";
		}
	}

	# get ticket ID to be used for backup/logdir
	@options = &ticketid(@options) unless (grep { /^--listbackups$/ } @options);

	# 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+)$/ ) { 
			$rrbackup{'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 { !/^\/.*/ } $rrbackup{'backuplistfile'}) { $rrbackup{'backuplistfile'}= &Cwd::cwd() . "/$rrbackup{'backuplistfile'}"; }
				if ( -T $rrbackup{'backuplistfile'}) { &printb("Using: $rrbackup{'backuplistfile'} as list of backups.\n"); }
				else { &printe("Error!  $rrbackup{'backuplistfile'} is not a valid text file or doesn't exist!  Exiting.\n"); }
			}				
		}		
		elsif ( $option =~ /^(--listbackups|--pretend|-p)$/ ) {
	# 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 eq '--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");
		}
		elsif ( $option eq '--skipexisting') {
			$conf{'skipexisting'} = 'yes';
			&printb("Option specified: $option\n");
			&printh("Existing accounts will be skipped over.\n");
			# toggle bakexisting to 'no'; --skipexisting takes precedence over --bakexisting
			(defined $conf{'bakexisting'} and $conf{'bakexisting'} eq 'yes') &&
				($conf{'bakexisting'} = 'no');
		}
		elsif ( $option eq '--bakexisting') {
			$conf{'bakexisting'} = 'yes';
			&printb("Option specified: $option\n");
			&printh("Warning:  existing accounts will automatically be backed up and removed without prompting.\n");
		}
		elsif ( $option =~ /^(-f|--force)$/) {
			&printb("Option specified: $option\n");
			for (my $i=1; $i < $termwidth; $i++) { print colored('*', 'bold red'); }
			&prints("\n\nWARNING:  you use the --force flag at your own risk.  Please understand what can happen if you use this before doing so.\n\n");
			for (my $i=1; $i < $termwidth; $i++) { print colored('*', 'bold red'); }
			print "\n";
			&printe("User aborted!  Exiting.\n") if (&continuequery == 0);
			$conf{'force'} = 'yes';
		}
		elsif ( $option eq '--' ) {
			&printh("'--' specified, treating remaining options as files to restore.\n");
			@restorefileslistfromcli = @options;
			@options = ();
			last;
		}
		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, $backupuser);
	return;
}

sub planchangecheck {
	my ($user, $originalplan) = @_;
	my $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 postkillacct {
	my ($homedir, $starttime, $killacctdie, $backupuser, $logfile, @log) = @_;

	# we want to flock an empty /var/cpanel/user/$backupuser file until we want to restore, to prevent someone else from restoring/creating an account with the same name
	my $cpfileandpath = "/var/cpanel/users/$backupuser";
	open my $cpfile, '>', $cpfileandpath
		or die "Unable to open $cpfileandpath for writing: [$!]";
	flock $cpfile, 2
		or die "Unable to flock $cpfileandpath: [$!]";

	# now let's log what the killacct
	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;

	# checks to make sure the killacct completed
	my $killacctmatch;
	foreach(@logfilein) { $killacctmatch++ and last if /^$backupuser account removed/; }

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

	# more checks
	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;
	sleep 3;

	# post-checks to remove remnants of removal
	&printb("Processing post-killacct checks\n\n");
	my $usersdbfile = '/var/cpanel/databases/users.db';
	my $usersdbfilebak = "$rrbackup{'backupdir'}/users.db";
	&printh('Backing up: ', colored($usersdbfile, 'bold white'), colored(' to ', 'green'), color('bold white'), "$usersdbfilebak\n");
	copy($usersdbfile, $usersdbfilebak) or die "Copy failed: $!";

	# read in/flock users.db
	open my $usersdbfilein, '<', $usersdbfile
		or die;
	flock $usersdbfilein, 2
		or die "Unable to lock $usersdbfile: [$!]";

	my @lines = <$usersdbfilein>;
	close $usersdbfile;

	&printh("Removing ", colored($backupuser, 'bold white'), color('green'), " references from ", colored("$usersdbfile\n", 'bold white'));

	# write out/flock users.db
	open my $usersdbfileout, '>', $usersdbfile
		or die;
	#flock $usersdbfileout, 2
	#	or die "Unable to lock $usersdbfile [$!]";

	foreach (@lines) { print $usersdbfileout $_ unless(/^  $backupuser(.*)?: 1$/); }
	close $usersdbfileout;
	my $cmd = '/scripts/updateuserdatacache';
	&prints("\nRemoval finished.  Running ", color('green'), $cmd, color('bold white'), " to update cache.\n");
	$logfile = 'updateuserdatacache.log';
	&lognotice($logfile, $backupuser);
	&logtofile($cmd, $logfile, $backupuser);
	&prints("\nUpdate user data cache finished.  Post-killacct adjustments completed.");
	&longsep;
	sleep 3;

	# close the file and therefore the flock on cpfile
	close $usersdbfileout;
}

sub postrestorecheck { # takes username as argument, mainly checks if OWNER is different than reselleruser and adjusts
	my ($user) = @_;
	my $backupuser = $user;
	&mysqlsucheck; # check for superuser privileges in MySQL restored from backup
	my $owner = &checkownerofcpaneluser($user);
	&printe("Can't continue; \$owner is empty!  This is likely because the restorepkg script failed.  Please review the logs in:\n    $rrbackup{'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$/) {
			&printh(" and on a Hostgator shared server.\n    Setting bandwidth unlimited and disk usage limit to 999999 MB\n");
			$bwlimit = 0;
			$dulimit = "999999M";
			&checkresetbwdiskquotas($bwlimit, $dulimit);
		}
		else {
			&printh(" but not on a Hostgator shared server.  Skipping bandwidth/disk usage limit resets.\n");
			return;
		}
	}
	else {
		if ($conf{'keepquotas'} and $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, $user);
		}
	}
	print "\n";
	&prints("Finished with post restore checks/adjustments.  Please check for errors.\n");
	&longsep;
	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('cyan'), @print, color('reset'); return; }

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

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

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

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

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 resellerorsharedcheck {
	# 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
	my ($type, $reselleroruser) = @_;
	return 1 if (!$reselleroruser || !$type);

	if ($type eq 'reseller') {
		if (! -s "/var/cpanel/users/$rrbackup{'reselleruser'}") { return 1; }
		elsif (! &resellercheckfile($rrbackup{'reselleruser'})) { return 1; }
		elsif (! -d &homedir($rrbackup{'reselleruser'})) { return 1; }
	}
	elsif ($type eq 'shared') {
		&printe("Reseller server detected ! --shared can't be used on reseller servers.  Exiting.\n") if (hostname =~ /^(\S+).websitewelcome.com$/);
	}

	# we need to do $rrbackup{'backupdir'}/$rrbackup{'logdir'} stuff here! - 11/04/11
	my $basedir = "/home/hgtransfer";
	mkdir $basedir if (! -d $basedir);
	my $rrdir = "/home/hgtransfer/rrbackups";
	mkdir $rrdir if (! -d $rrdir);
	my $user = ($rrbackup{'shareduser'}) ? $rrbackup{'shareduser'} : $rrbackup{'reselleruser'};
	$rrbackup{'backupdir'} = (defined $rrbackup{'ticketid'} and $rrbackup{'ticketid'} =~ /(([A-Z]{3}-)?[0-9]{8})/) ? "$rrdir/$rrbackup{'ticketid'}" : "$rrdir/${user}-$conf{'date'}";
		
	if (defined $rrbackup{'ticketid'} and $rrbackup{'ticketid'} =~ /(([A-Z]{3}-)?[0-9]{8})/ and not defined $rrbackup{'ticketidset'}) {
		if (-e $rrbackup{'backupdir'}) {
			my $epoch = time;
			&printh("File or directory found at $rrbackup{'backupdir'}, moving out of the way to $rrbackup{'backupdir'}-old.$epoch\n");
			move($rrbackup{'backupdir'}, $rrbackup{'backupdir'} . "-old.$epoch")
				or &printe("Unable to move $rrbackup{'backupdir'} to $rrbackup{'backupdir'}-old.$epoch");
		}
		$rrbackup{'ticketidset'} = 1;
	}
	mkdir $rrbackup{'backupdir'} if (! -d $rrbackup{'backupdir'});
	$rrbackup{'logdir'} = "$rrbackup{'backupdir'}/logs";
	mkdir $rrbackup{'logdir'} if (! -d $rrbackup{'logdir'});
	# return 0 means he is a reseller
	return 0 if $type eq 'reseller';
	return 1 if $type eq 'shared';
}

sub restorebackup { # takes a full path as argument
	my ($backup) = @_;
	my $backupuser;
	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'};

	unless ( $backupuser eq $owner ) {
		my @cpmovefiles;
		push(@cpmovefiles, "/$_/cpmove-$backupuser.tar.gz") foreach (('home', 'home2', 'home3', 'root', 'usr', 'usr/home', 'web'));
		my $appendednewnameforcpmove = ".renamed-by-rrbackups-for-$backupuser-$conf{'date'}";
		foreach my $cpmovefile (@cpmovefiles) {
			if ( -f $cpmovefile ) {
				print "\n";
				&printh("A cpmove file for ", color('bold white'), $backupuser, color('green'), " is present at: \n    ->\t", colored($cpmovefile, 'bold white'), color('green'), "\n    Appending filename with ", colored($appendednewnameforcpmove, 'red'), color('green'), " to keep cPanel from restoring it...\n");
				&move($cpmovefile, $cpmovefile . $appendednewnameforcpmove) || die "Can't move $cpmovefile to $cpmovefile" . "$appendednewnameforcpmove at $!";
			}
		}
		print "\n";	
		&printb("Proceeding with restore...\n");
		&longsep;
		&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;
		}

		local $SIG{'INT'} = \&restorecomplete;

		unless (defined $conf{'force'} and $conf{'force'} eq 'yes') {
		my $defaultanswer = 'continue';
		&printq("Do you wish to continue with the restore (continue), skip to the next backup (skip), or skip the rest of the backups (last)? [$defaultanswer] : ");
			my $answer;
			while($answer = <>) {
				if ( $answer =~ /^(yes|y|continue)$/i ) 		{	$answer = 1; last; }
				elsif ( $answer =~ /^(no?|skip|next)$/i ) 	{	$answer = 0; last; }
				elsif ( $answer =~ /^(stop|last|end)$/i ) { $answer = 2; last; }
				elsif ( $answer =~ /^$/ ) 			{	$answer = 1; last; }
				else { $_ = $answer; chomp; s#\n##g;  s#\r##g; $answer = $_; &printh("Invalid entry, \"$answer\".  Type continue, skip, or last [$defaultanswer] : "); }
			}
			if ($answer == 2) {
				#foreach (@backups) { push @restoresfailed, $_; }
				&printb("Finishing up...\n");
				&restorecomplete;
			}
			elsif ($answer == 0) { return 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");
		}
		local $SIG{'INT'} = \&catchsigint;
		# check if cPanel user exists, if so, prompt for backup/removal
		if ( -s $cpfile ) {
			&longsep;
			&printh("User '$backupuser' exists");
			if (defined $conf{'skipexisting'} and $conf{'skipexisting'} eq 'yes') {
				&printh(" and --keepexisting argument specified!  Skipping existing account to next user...\n");
				push @restoresfailed, $backup;
			}
			else {
				&printh("\nYou have the option of collecting account information, backing up, removing, then restoring.\n\n");
				if ( defined $conf{'bakexisting'} and $conf{'bakexisting'} eq 'yes' or &continuequery == 1 ) { # we need to do something here, sir - 10/24/11
					print "\n";
					my ($originalip, $originalplan) = &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
					&longsep;
					&restorebackupnow($backupuser, $backup, $originalip, $originalplan);
					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($backupuser, $backup);
		}
	}
	else { 
		&printh("The backupuser, $backupuser, is the same as the reseller specified!  Are you crazy? Skipping this backup.\n");
		push @restoresfailed, $backup;
	}
	return;
}

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

	my $starttime = [Time::HiRes::gettimeofday()];

	my @log = `$conf{'nice'} $conf{'nicevalue'} $conf{'restorepkg'} $localbackup 2>&1` || &printe("Error encountered during restore!  Please review the logs at: ", color('yellow'), "$rrbackup{'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 (defined $restorecompletematch and $restorecompletematch == 1) { 
		my $runtime = ceil(Time::HiRes::tv_interval($starttime));
		print "\n"; &printh("Restorepkg found no issues restoring, was able to successfully complete the restore, and finished in $runtime seconds.\n\n"); sleep 3; }
	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'.");
	&longsep;
	# restore SIGINT default
	local $SIG{'INT'} = \&catchsigint;

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

	&ipchangecheck($backupuser, $originalip);
	&planchangecheck($backupuser, $originalplan);

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

	&accountinfo($backupuser);

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

sub restorecomplete {
&longsep;
	print colored("\n+-++-++-++-++-++-++-+ +-++-++-++-++-++-++-++-+\n", 'bold blue');
	print colored("|R||E||S||T||O||R||E| |C||O||M||P||L||E||T||E|\n", 'bold blue');
	print colored("+-++-++-++-++-++-++-+ +-++-++-++-++-++-++-++-+\n\n", 'bold blue');
	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 colored("    $_\n", 'bold white'); }
	}
	else { &printh("No backups were restored\n"); }
	print "\n";

if (!$rrbackup{'shareduser'}) {
	if (@restoresfailed > 0 ) {
		&printb("Failed restores:    \n");
		foreach (sort @restoresfailed) { print colored("    $_\n", 'red'); }
		print "\n";
	}
	elsif (@restoresfailed == 0 and @restorescompleted == 0) { &printb("Skipped backups:\n"); foreach (sort @backups) { print colored("    $_\n", 'red'); } print "\n"; }
	else { &printh("No restores failed. Good!\n"); }

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

	if (@killacctfailed) { 
		&printh("The following accounts failed to be killed:\n\n");
		print "    $_\n" foreach (sort @killacctfailed); print "\n";
	}
	else { print colored("No accounts failed to be killed.\n", 'green'); }
}	

	if (@backupscompleted) {
		&printb("\nThe following pre-restore backups were created:\n");
		print colored("$_\n", 'bold white') foreach(sort @backupscompleted);
	}

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

	&printb("Log files can be found at:\n    ", color('yellow'), "$rrbackup{'logdir'}\n\n"); 

	if (@backups > 0) {
		&printb("And finally, all the backups we were tasked with restoring:\n");
		print "    $_\n" foreach @backups;
		print "\n";
	}

	if (@restorescompleted > 0) { 
		print "\n";
		if ($rrbackup{'shareduser'}) {
			&printb("Restore finished for $rrbackup{'shareduser'}.\n");
			print "Please be sure to change their plan to the one specified in billing if this was not changed during the restore process.\n\n";
		}
		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"; }
	exit;
}

sub rrbackups {
	($rrbackup{'reselleruser'}) = @_;
	&printe("Reseller not defined.  Use: --reseller=username and try again.\n") if (!defined($rrbackup{'reselleruser'}));
	if ( &resellerorsharedcheck('reseller', $rrbackup{'reselleruser'}) == 0 ) {
		print "\n";
		&printb("Here are the backups I will attempt to restore for reseller ", colored("$rrbackup{'reselleruser'}", 'bold white'), color('cyan'), ": \n\n");

		if ($rrbackup{'backuplistfile'} and -T $rrbackup{'backuplistfile'}) {
			open my $backuplistfilein, "<", $rrbackup{'backuplistfile'} || &printe("Can't open file $rrbackup{'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;
		}
		elsif (@restorefileslistfromcli > 0) {
			#@backups = @restorefileslistfromcli;
			foreach (@restorefileslistfromcli) {
				push(@backups, &Cwd::cwd . "/$_") and next unless m#^(/|\.(\.)?)#;
				push @backups, $_;
			}
		}
		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) {
			print colored("    $_\n", 'bold white') foreach sort @backups;
			print "\n";
			&printe("Script must be run as root to restore!  Exiting.\n") if $> != 0;
			if ( defined $conf{'force'} and $conf{'force'} eq 'yes' or &continuequery == 1 ) {
				foreach my $backup (sort @backups) {
					if ( -s $backup ) {
						&restorebackup($backup);
					}
					else {
						push @restoresfailed, $backup; &printh("Backup file $backup is missing or invalid!  Skipping to next backup.\n\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 {
	my ($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;
		my $newbackuplocation = $backup = "$rrbackup{'backupdir'}/$backupfile";
		print "\n";
		&printb("Moving provided backup:\n    $originalbackuplocation to $newbackuplocation ...\n\n");
		if (-f $originalbackuplocation) { &move($originalbackuplocation, $newbackuplocation) || die("Can't move $originalbackuplocation to $newbackuplocation at $!"); }
		elsif (-d $originalbackuplocation) { &printe("Uh oh:  $originalbackuplocation isn't a file but is instead a directory.  Try again!\n"); }

		# THE MEAT!
		&restorebackup($backup);

		my $backupdestination = &homedir($rrbackup{'shareduser'}) . "/$backupfile";
		print "\n";

		if ( @restorescompleted == 1 ) {
			&printb("Moving provided backup:\n    ", colored($backup, 'bold white'), color('cyan'), ' to ', color('bold white'), "${backupdestination}...\n\n");
			&move($backup, $backupdestination) || die("Can't move $backup to $backupdestination at $!");
			$rrbackup{'backup'} = $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 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+)$/ ) {
			&sharedbackuprestorenow($1);
		}
		elsif ( $option =~ /^--single=\.\.(\S+)$/ ) {
			shift @options;
			my $backup = $1;
			my @cwddoubledot = split(/\//, &Cwd::cwd);
			pop @cwddoubledot;
			$backup = join("/", @cwddoubledot) . "$backup";
			&sharedbackuprestorenow($backup);
		}			
		elsif ( $option =~ /^--single=\.(\S+)$/ ) {
			shift @options;
			&sharedbackuprestorenow(&Cwd::cwd . $1);
		}
        elsif ( $option =~ /^--single=(\S+)$/ ) {
			$rrbackup{'reselleruser'} = 'root';
			unless ($1 =~ m#/(.*)#) { &sharedbackuprestorenow(&Cwd::cwd . "/$1"); }
			else { &sharedbackuprestorenow($1); }
        }
        else {
            &printe("Invalid option, '$option', specified!  Please remove and try again.\n");
        }
    }
	return;
}

sub shareduser {
    ($rrbackup{'shareduser'}) = @_;
	my ($option, @options) = @_;
    &resellerorsharedcheck('shared', $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
    &sharedoptions(@options);
	return;
}

sub ticketid {
	my ($potentialticketid, @options) = @_;
	if ($potentialticketid) {
		@options = &ticketidcheck($potentialticketid, @options);
	}
	else {
		$rrbackup{'ticketid'} = &ticketidcheck(&ticketidprompt);
	}
	return @options;
}

sub ticketidcheck {
	my ($potentialticketid, @options) = @_;
	while (1) {
		if ($potentialticketid =~ /^$/) {
			$rrbackup{'ticketid'} = (defined($rrbackup{'shareduser'})) ? $rrbackup{'shareduser'} : $rrbackup{'reselleruser'};
			&printb("No ticket specified, using the default format, ", colored("$rrbackup{'ticketid'}-$conf{'date'}", 'bold white'), "\n\n");
			last;
		}
		elsif ($potentialticketid =~ /^(([A-Z]{3}-)?[0-9]{8})$/) {
			$rrbackup{'ticketid'} = $potentialticketid;
			&printb("Ticket specified: $rrbackup{'ticketid'}\n");
			&printh("Notice:  this will be used as part of the backup/log directory name.  If the directory already exists, we'll let you know.\n");
			my %delh;
			$delh{$potentialticketid} = ();
			@options = (@options) ? grep {! exists $delh{$_} } @options : ();
			&longsep;
			last;
		}
		else {
			unless (defined $rrbackup{'ticketidprompt'} and $rrbackup{'ticketidprompt'} eq 'yes') {
				&printh("Invalid ticket ID specified: $potentialticketid.  This might be an option, so pushing it back to the arguments list.\n");
				unshift @options, $potentialticketid;
				$rrbackup{'ticketidprompt'} = 'yes';
			}
			$rrbackup{'ticketid'} = &ticketidprompt; last;
		#	print "\n";
		#	$rrbackup{'ticketid'} = (defined($rrbackup{'shareduser'})) ? $rrbackup{'shareduser'} : $rrbackup{'reselleruser'};
		#	&printb("No valid ticket specified, using the default format, ", colored("$rrbackup{'ticketid'}-$conf{'date'}", 'bold white'), "\n\n");
		#	last;
		}
	}
	return @options;
}

sub ticketidprompt {
	&printh("Please enter the ticket ID, or press enter to use the user/reseller as the backup and log directory.\n\n");
	print colored("    Ticket ID : ", 'bold white');
	my $ticketid = <>;
	chomp $ticketid;
	return $ticketid;
}

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