#!/usr/bin/env perl

use strict;
use Getopt::Long;

my $backuptmp	= 'backuptmp';
my $restorebin	= '/usr/local/cpanel/bin/restorepkg';
my $restorearg	= '--force';
my $location	= 'cpbackup';
my $user	= '';
my $type	= '';
my $ip		= '';
my $force	= 0;
my $reseller	= 0;
my $archived	= 0;
my $list	= 0;
GetOptions(
        "user|u=s"	=>      \$user,
	"type|t=s"	=>	\$type,
	"ip|i=s"	=>	\$ip,
	"force|f"	=>	\$force,
	"archived|a"	=>	\$archived,
	"listla"	=>	\$list,
);

&usage() unless ( $user && ( $type || $list ) );

if ( $list ) {
	&list_backups($user);
	exit;
}

$location = 'archived-backups' if ( $archived );

if ( !-e $restorebin ) {
	die "Can't find $restorebin\n";
} elsif ( !-x $restorebin ) {
	die "$restorebin is not excecutable\n";
}

my $backupnum = $1 if ( (getpwnam($user))[7] =~ m%/home(\d*)/% );
my $target_dir = "/home$backupnum";
$target_dir = '' if ( `/bin/mountpoint /home$backupnum` !~ m/ is a mountpoint$/  || system("[ -w /home$backupnum ]") != 0 );
if ( eval( system("touch $target_dir/writable_fs_test 2&>1 > /dev/null") ) ) {
	$target_dir = '';
} else {
	unlink "$target_dir/writable_fs_test";
}
my $srcpath = "/backup$backupnum/$location/$type/$user";
my $tmppath = "$target_dir/$backuptmp/$location/$type/$user";
if ( !-d $srcpath ) {
	die "$srcpath doesn't exist or backups aren't mounted.  Please fix and try again\n";
}
if ( -f "$srcpath/resellerconfig/my_reseller-limits.yaml" && -s "$srcpath/resellerconfig/resellers" ) {
	print "Restoring reseller settings\n";
	$reseller = 1;
	$restorearg .= " --allow_reseller --unrestricted";
}
if ( $ip && $ip =~ m/^((\d+\.\d+\.\d+\.\d+)|y)$/ ) {
	$restorearg .= " --ip=$ip";
}
if ( !$force ) {
	@ARGV = undef;
	print "Attempt to restore $type backup for $user? [Y|n]\n";
	exit unless ( <STDIN> =~ m/^y/i );
}

die "Couldn't find cpuser file in backup: $srcpath/cp/$user\n" if ( !-f "$srcpath/cp/$user" );

system("mkdir -pv $tmppath && chmod 0700 $tmppath") == 0 or die "Could not create $tmppath: $!\n";
die "Can't find $tmppath\n" if ( !-d $tmppath );
my $cmd = "/bin/mount --bind $srcpath $tmppath";
system("$cmd") == 0 or die "Couldn't bind mount $srcpath on $tmppath: $!\n";
$cmd = "$restorebin $restorearg $tmppath";
system("$cmd") == 0 or print "Failed to restore $type backup for $user.  restorepkg failed\n";
system("/bin/umount $tmppath && rm -r $tmppath") == 0 or print "Failed to clean up tmpdir $tmppath: $!\n";
print "\n\nRestore Complete\n\n";

sub list_backups {
	my $user = shift;
	my %data;
	if ( !getpwnam($user) || !-e "/var/cpanel/users/$user" ) {
		print "Local cPanel user $user doesn't exist\n";
	}
	foreach my $cat ( "cpbackup", "archived-backups" ) {
		foreach my $ltype ( "daily", "weekly", "monthly" ) {
			if ( -f "/backup/$cat/$ltype/$user/lastgenerated" ) {
				$data{$cat}{$ltype} = (stat("/backup/$cat/$ltype/$user/lastgenerated"))[9];
			}
		}
	}
	if ( scalar( keys %data ) < 1 ) {
		print "No backups found for $user, check username and NFS mounts\n";
	} else {
		print "\nBackups available:\n";
		foreach my $cat ( keys %data ) {
			foreach my $ltype ( keys %{ $data{$cat} } ) {
				if ( $cat =~ m/archived/ ) {
					print "$ltype (archived): " . localtime($data{$cat}{$ltype}) . "\n";
				} else {
					print "$ltype: " . localtime($data{$cat}{$ltype}) . "\n";
				}
			}
		}
		print "\n";
	}
}

sub usage {
	print qq{$0 usage:
\t$0 --user|-u=<user> --type|-t=<daily|weekly|monthly> [--list|-l] [--archived|-a] [--ip=(y|n|custom IP)] [--force|-f]

\t--user|-u\tcPanel user to restore
\t--type|-t\tBackup type to restore (daily|weekly|monthly)
\t--archived|-a\tRestore from archived-backups instead of standard
\t--ip\t\tRestore account with a dedicated IP (y|n|custom IP)
\t--force|-f\tForce restore without prompt
\t--list|-l\tList backups available for a cPanel user

};
	exit;
}
