#!/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;
GetOptions(
        "user|u=s"	=>      \$user,
	"type|t=s"	=>	\$type,
	"ip|i=s"	=>	\$ip,
	"force|f"	=>	\$force,
	"archived|a"	=>	\$archived,
);

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

$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";
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 usage {
	print qq{$0 usage:
\t$0 --user|-u=<user> --type|-t=<daily|weekly|monthly> [--archived|-a] [--ip=(y|n|custom IP)] [--force|-f]
};
	exit;
}
