#!/usr/bin/env perl

use strict;
use Getopt::Long;
use Sys::Hostname;
use YAML qw( LoadFile );
use IPC::Open3;
use JSON;

my $eig_backup_config = '/opt/eig_linux/etc/eig_backup.conf';
my $backup_server_config = '/opt/eig_linux/etc/backup_server_info.conf';
my $backuptmp	= 'backuptmp';
my $restorebin	= '/usr/local/cpanel/bin/restorepkg';
my $restorearg	= '--force';
my $location	= 'cpbackup';
my $hostname	= hostname;
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 ) );

my %eig_backup_config;
load_config();

my $backupnum = $1 if ( (getpwnam($user))[7] =~ m%/home(\d*)/% );
my $backupkey = (-f '/admin/hgbackupdir/backupkey') ? '/admin/hgbackupdir/backupkey' : '/home/hgbackupdir/backupkey';

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 $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 = "rsync -a -e \"ssh -i $backupkey\" root\@$backup_server_config->{backup_ip}:/home/$hostname$srcpath/. $tmppath/.";
print "Copying files from backup server\n";
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("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;
    my $archived_only = 0;
    die "Dirty user found '$user'" unless $user =~  /^[a-z0-9.-_]++$/;
	if ( !getpwnam($user) || !-e "/var/cpanel/users/$user" ) {
		print "Local cPanel user $user doesn't exist\n";
        $archived_only = 1;
	}
    my $script=<<'EOF';
#!/usr/bin/env perl
use JSON;
my $return;
EOF
    $script .= 'my $user  = "'  . $user . "\";\n";
    $script .= 'my $home = "/home/' . $hostname . "\";\n";
    unless ($archived_only) {
        $script .= 'my $homenum = "'  . $backupnum . "\";\n";
        $script .=<<'EOF';
foreach my $ltype ( "daily", "weekly", "monthly" ) {
   if ( -f "$home/backup$homenum/cpbackup/$ltype/$user/lastgenerated" ) {
        $return->{"cpbackup"}->{$ltype} = (stat("$home/backup$homenum/cpbackup/$ltype/$user/lastgenerated"))[9];
    }
}
EOF
    }
    $script .=<<'EOF';
opendir my $dh, $home;
my @backupdirs = grep {-d "$home/$_" && m/^backup/}  readdir($dh);
foreach my $ltype ( "daily", "weekly", "monthly" ) {
    foreach my $backupdir (@backupdirs){
        if ( -f "$home/$backupdir/archived-backups/$ltype/$user/lastgenerated" ) {
            $return->{"archived-backups"}->{$ltype} = (stat("$home/$backupdir/archived-backups/$ltype/$user/lastgenerated"))[9];
        }
    }
}
my $json=eval { encode_json($return) } || {};
print "$json";
EOF
    $data = ssh_script($script);
    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;
}

sub load_config {
  open(DC, "<$eig_backup_config")
    or die "Unable to open EIG Backup config file $eig_backup_config for reading: $!";
  foreach my $line (<DC>) {
    $eig_backup_config{$1} = $2 if ($line =~ m/^([^=]+?)=(.+)$/);
  }
  close(DC);
  if ( $eig_backup_config{ssh_sync} ) {
    $backup_server_config = LoadFile( $backup_server_config );
    if ( !$backup_server_config->{backup_ip} ) {
      die "No SSH host found in $backup_server_config!\n"
    }
  }
}

sub ssh_script{
    my $script = shift;
    my $proc="ssh -i $backupkey  -q -o LogLevel=QUIET -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=30 -o ServerAliveInterval=15 -l root $backup_server_config->{backup_ip} 'cat | perl'";
    my ($stdout, $stderr, $exit_code);
    my $pid=open3(\*IN, \*OUT, \*ERR, $proc);
    print IN $script;
    close IN;
    chomp ($stdout = join '', <OUT>);
    close OUT;
    chomp ($stderr = join '', <ERR>);
    close ERR;
    waitpid($pid, 0);
    $exit_code=$? >> 8;
    die "SSH failed: $stderr\n" if ($exit_code); 
    my $stat=eval { decode_json($stdout) } || {};
    return $stat;
}
