#!/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 $skipaccount = 0;
my $skiphome = 0;
my $list = 0;
my $backupnum;
GetOptions(
    "user|u=s"      => \$user,
    "type|t=s"      => \$type,
    "ip|i=s"        => \$ip,
    "force|f"       => \$force,
    "archived|a"    => \$archived,
    "list|l"        => \$list,
    "partition|p=i" => \$backupnum,
    "skipaccount"   => \$skipaccount,
    "skiphome"      => \$skiphome,
);

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

my %eig_backup_config;
load_config();

$backupnum = $1 if (!$backupnum && (getpwnam($user))[7] =~ m%/home(\d*)/% );

if (!$list && !$backupnum && `/bin/mountpoint /backup` !~ m/ is a mountpoint$/ && !getpwnam($user)){
    print "Backup partition for ".$user." not found by default, using extended detection...\n";
    my $available = `grep backup[0-9] /proc/mounts`;
    my @available = split '\n', $available;
    foreach my $part(@available){
        my @spl = split ' ', $part;
        my @fl = glob(@spl[1]."/archived-backups/*/".$user);
        if( @fl > 0){
            print "Found backups for ".$user." on ".@spl[1]."\n";
            if (!defined $backupnum){
                $backupnum = substr @spl[1], -1;
            }else{
                die "Unable to determine correct /backup partition for ".$user.". It appears the account is on multiple /backup partitions\nPlease run -list and choose a parition with the -p flag.\n";
            }
        }
    }
}

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" );

##Time to actually run the restore now
my $cmd;
unless ($skipaccount){
    system("mkdir -pv $tmppath && chmod 0700 $tmppath") == 0 or die "Could not create $tmppath: $!\n";
    die "Can't find $tmppath\n" if ( !-d $tmppath );
    $cmd = qq(rsync -a -e "ssh -i $backupkey" --exclude=homedir root\@$backup_server_config->{backup_ip}:/home/$hostname$srcpath/. $tmppath/.);
    print "Copying account files from backup server\n";
    system("$cmd") == 0 or die "Couldn't copy files from $srcpath to  $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";
}
unless ($skiphome){
    print "Restoring homedir files\n";
    my $homedir = (getpwnam("$user"))[7] or die "failed to find passwd entry for $user\n";
    die "Homedir does not exist for $user\n" if ( ! -d $homedir );
    $cmd = qq(rsync -a -e "ssh -i $backupkey" root\@$backup_server_config->{backup_ip}:/home/$hostname$srcpath/homedir/. $homedir/.);
    system("$cmd") == 0 or die "Unable to restore homedir files\n";
    $cmd = qq(/root/bin/perms $user);
    print "Running perms for $user\n";
    system("$cmd") == 0 or die "Unable to run perms for $user\n";
}
print "\n\nRestore Complete\n\n";

##subs below here

sub list_backups {
    my $user = shift;
    my $data;
    my $archived_only = 0;
    die "Dirty user found '$user'" unless $user =~  /^[a-z0-9.-_]++$/;
    my $script=<<'EOF';
#!/usr/bin/env perl
use JSON;
my $return;
EOF
    $script .= 'my $user  = "'  . $user . "\";\n";
    $script .= 'my $home = "/home/' . $hostname . "\";\n";
    $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){
        my $backupnum = $1 if ($backupdir =~ m/backup(\d++)/);
        if ( -f "$home/$backupdir/cpbackup/$ltype/$user/lastgenerated" ) {
            $return->{"cpbackup"}->{$backupnum}->{$ltype} = (stat("$home/$backupdir/cpbackup/$ltype/$user/lastgenerated"))[9];
        }
        if ( -f "$home/$backupdir/archived-backups/$ltype/$user/lastgenerated" ) {
            $return->{"archived-backups"}->{$backupnum}->{$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 $num (keys %{ $data->{$cat} }) {
                foreach my $ltype ( keys %{ $data->{$cat}->{$num} } ) {
                    if ( $cat =~ m/archived/ ) {
                        print "backup$num/$ltype (archived): " . localtime($data->{$cat}->{$num}->{$ltype}) . "\n";
                    } else {
                        print "backup$num/$ltype: " . localtime($data->{$cat}->{$num}->{$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
\t--partition|-p\tForce the partition number you want to restore from
\t--skipaccount\tSkip the cpanel account restore
\t--skiphome\tSkip the home rsync

};
    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;
}
