#!/usr/bin/env perl
use strict;
use Getopt::Long;
use Sys::Hostname;
use YAML qw( LoadFile Load );
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 $location = 'cpbackup';
my $hostname = hostname;
my $user = '';
my $type = '';
my $ip = '';
my $subpath = '';
my $domain = '';
my $force = 0;
my $reseller = 0;
my $archived = 0;
my $restoreaccount = 0;
my $restorehome = 0;
my $full = 0;
my $list = 0;
my $prebackup = 0;
my $prebackupname = time;
my $backupnum;
my $rsyncargs = "";
my $restoreargs = "";
my $singledb = "";
my $validoptions = 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,
    "path=s"        => \$subpath,
    "domain=s"      => \$domain,
    "backup|b"      => \$prebackup,
    "backupname=s"  => \$prebackupname,
    "full"          => \$full,
    "account"       => \$restoreaccount,
    "home"          => \$restorehome,
    "rsyncargs=s"   => \$rsyncargs,
    "restoreargs=s" => \$restoreargs,
    "singledb=s"    => \$singledb,
);
usage() && print "\n" && exit if (!$validoptions);
usage() && print "\n" && exit unless ( $user && ( $type || $list ) );
die "Please choose path or domain but not both" if ($subpath && $domain);
$restorehome = 1 if ($domain || $subpath);
$full = 1 if (!($restorehome||$restoreaccount||$domain||$subpath||$singledb));
$restoreargs .= ' --force';

my %eig_backup_config;
load_config();
my $backupkey = (-f '/admin/hgbackupdir/backupkey') ? '/admin/hgbackupdir/backupkey' : '/home/hgbackupdir/backupkey';

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

#setting up all the vars and locations we need
my $backuppath;
my $driveusage = get_drive_usage();
my $logdir = "/var/log/eig_backup/user_logs/$user";
my $homedir = (getpwnam($user))[7];
die_user("no homedir found and we aren't restoring account?") if (!$homedir && (!$full && !$restoreaccount));
$backupnum = find_partition() unless $backupnum;
my $homenum = ($homedir =~ m|/home(\d*)/|) ? $1 : $backupnum;
$location = 'archived-backups' if ( $archived );
die_user("$restorebin is not executable") if ( !-x $restorebin );
my $target_dir = "/home$homenum";
$target_dir = '' if ( not defined $driveusage->{"/home$homenum"}  || system("[ -w /home$homenum ]") != 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";
die_user("Couldn't find cpuser file in backup: $srcpath/cp/$user") if ( !-f "$srcpath/cp/$user" );
die_user("$srcpath doesn't exist or backups aren't mounted.  Please fix and try again") if (!-d $srcpath);
if ( -f "$srcpath/resellerconfig/my_reseller-limits.yaml" && -s "$srcpath/resellerconfig/resellers" ) {
    log_user("Restoring reseller settings");
    $reseller = 1;
    $restoreargs .= " --allow_reseller --unrestricted";
}
$restoreargs .= " --ip=$ip" if ( $ip && $ip =~ m/^((\d+\.\d+\.\d+\.\d+)|y)$/ );
die_user("Path does not look to be valid") if ($subpath =~ m|[.]{2}/|);
if ($domain){
    my $resp=qx(whmapi1 domainuserdata domain=$domain);
    my $domain_data=Load($resp);
    die_user("$domain does not look to be owned by $user") unless $domain_data->{'data'}->{'userdata'}->{'user'} = $user;
    if ($domain_data->{'data'}->{'userdata'}->{'documentroot'} =~ m|$homedir/(.*)|){
        $subpath = $1;
    }else{
        die_user("$domain is not within $homedir/");
    }
}

#Lets get some confirmations
if ( !$force ) {
    @ARGV = undef;
    if ($full){
        print "Attempt to restore the full $type backup for $user? [Y|n]\n";
    }elsif ($restoreaccount){
        print "Attempt to restore the cpanel account $type backup for $user? [Y|n]\n";
    }elsif ($restorehome){
        my $pathmsg = ($subpath ? " on path $subpath": "");
        print "Attempt to restore the home $type backup for $user$pathmsg? [Y|n]\n";
    }elsif ($singledb){
        print "Attempt to restore $singledb from the $type backup? [Y|n]\n";
    }
    exit unless ( <STDIN> =~ m/^y/i );
}
if ($prebackup){
    mkdir "/home$homenum/hgbackupdir" unless (-d "/home$homenum/hgbackupdir");
    $backuppath = "/home$homenum/hgbackupdir/$user.$prebackupname";
    mkdir $backuppath unless (-d $backuppath);
}

#time to actually kick off the restore now. 
log_user("Starting Restore");
restore_db() if $singledb;
restore_account() if $restoreaccount || $full;
restore_home($subpath) if $restorehome || $full;
log_user("Restore Complete");

##Subs below here
sub get_drive_usage{
    my $driveusage;
    for my $line ( qx(df -P) ){
        my ($device, $total, $used, $availble, $capacity,  $mount) = split /\s+/, $line;
        $driveusage->{$mount}->{'total'} = $total;
        $driveusage->{$mount}->{'used'} = $used;
        $driveusage->{$mount}->{'cpacity'} = $1 if ($capacity =~ m/(\d+)%/);
    }
    return $driveusage;
}
sub prebackup_home{
    die_user("Homedir does not exist for $user\n") if ( ! -d $homedir );
    log_user("Starting home backup at $backuppath/$user.tar.gz");
    
    #doing a space check here, if quota + current usage is over 95% we are bailing.
    my $mount = defined $driveusage->{"/home$homenum"} ? "/home$homenum" : "/";
    chomp(my @quotas = qx(repquota -u $mount));
    my $userquota;
    foreach my $line (@quotas){
        $userquota = $1 if ($line =~ m/^$user\s+--\s+(\d+)/);
    }
    die_user("Failed to find usage for $user, aborting prerestore backup") unless $userquota;
    die_user("$mount does not have enough space for prerestore backup, aborting")
            if (($driveusage->{$mount}->{'used'} + $userquota)*100/$driveusage->{$mount}->{'total'} >= 95);

    my $relpath = $subpath || "./";
    if (-e "$homedir/$relpath"){
        system("tar -czf $backuppath/$user.tar.gz -C $homedir $relpath") == 0 or die_user("Home backup reported failure: $!");
    }else{
        log_user("Skipping home backup as $homedir/$relpath does not exist");
    }
    log_user("File backup complete!");
}
sub prebackup_account{
    log_user("Making account backup at $backuppath/cpmove-$user.tar.gz");
    system("/scripts/pkgacct --skiphomedir $user $backuppath >/dev/null") == 0 or die_user("Prerestore account backup reported failure: $!");
    log_user("Account backup completed!");
}
sub prebackup_db{
    log_user("Making Mysql backup at $backuppath/$singledb.sql");
    system("mysqldump $singledb > $backuppath/$singledb.sql") == 0 or die_user("Prerestore mysql backup reported failure: $!");
    log_user("Mysql $singledb backup completed!");
}
sub log_user{
    my $message = shift;
    mkdir $logdir unless (-d $logdir);
    open my $log, ">>", "$logdir/sshrestore.log";
    print $log time . ":$user:INFO: $message\n";
    close $log;
    print "$message\n"
}
sub die_user{
    my $message = shift;
    mkdir $logdir unless (-d $logdir);
    open my $log, ">>", "$logdir/sshrestore.log";
    print $log time . ":$user:ERROR: $message\n";
    close $log;
    die "$message\n";
}
sub restore_account{
    prebackup_account() if $prebackup;
    system("mkdir -pv $tmppath && chmod 0700 $tmppath") == 0 or die_user("Could not create $tmppath: $!");
    die_user("Can't find $tmppath") if ( !-d $tmppath );
    my $cmd = qq(rsync -av -e "ssh -i $backupkey" --exclude=homedir root\@$backup_server_config->{backup_ip}:/home/$hostname$srcpath/. $tmppath/. 2>&1 >> $logdir/sshrestore.log);
    log_user("Copying account files from backup server");
    system("$cmd") == 0 or die_user("Couldn't copy files from $srcpath to  $tmppath: $!");
    log_user("Starting cpanel account restore");
    $cmd = "$restorebin $restoreargs $tmppath 2>&1 >> $logdir/sshrestore.log";
    system("$cmd") == 0 or log_user("Failed to restore $type backup for $user.  restorepkg failed");
    log_user("Cpanel account restore finished");
    system("rm -r $tmppath") == 0 or log_user("Failed to clean up tmpdir $tmppath: $!");
}
sub restore_home{
    prebackup_home($subpath) if $prebackup;
    my $homedir = (getpwnam("$user"))[7] or die_user("failed to find passwd entry for $user");
    die_user("Homedir does not exist for $user\n") if ( ! -d $homedir );
    log_user("Restoring $homedir/$subpath files");
    my $cmd = qq(rsync -av -e "ssh -i $backupkey" $rsyncargs root\@$backup_server_config->{backup_ip}:/home/$hostname$srcpath/homedir/$subpath/ $homedir/$subpath/ 2>&1 >> $logdir/sshrestore.log);
    system("$cmd") == 0 or die_user("Unable to restore homedir files");
    $cmd = qq(/root/bin/perms $user 2>&1 >> $logdir/sshrestore.log);
    log_user("Running perms for $user");
    system("$cmd") == 0 or die_user("Unable to run perms for $user");
}
sub restore_db {
    prebackup_db() if $prebackup;
    die_user("Invalid db name") unless ($singledb =~ m/^\w+\_.+/g);
    system("mkdir -pv $tmppath/mysql && chmod 0700 $tmppath") == 0 or die_user("Could not create $tmppath: $!");
    die_user("Can't find $tmppath") if ( !-d $tmppath );
    my $cmd = qq(rsync -av -e "ssh -i $backupkey" --exclude=homedir root\@$backup_server_config->{backup_ip}:/home/$hostname$srcpath/mysql/. $tmppath/mysql/.  --include='$singledb.sql' --include='$singledb.create' --exclude='*'  2>&1 >> $logdir/sshrestore.log);
    log_user("Copying mysql from backup server");
    system("$cmd") == 0 or die_user("Couldn't copy mysql backup from $srcpath/mysql/  to  $tmppath: $!");
    die_user("no valid sql dump found") unless qx(tail -n 1 $tmppath/mysql/$singledb.sql) =~ m/-- Dump completed/;
    die_user("no valid create dump found") unless qx(tail -n 1 $tmppath/mysql/$singledb.create) =~ m/-- Dump completed/;
    log_user("Creating $singledb");
    system("mysql < $tmppath/mysql/$singledb.create") == 0 or die "Unable to create $singledb: $!";
    log_user("Restoring $singledb");
    system("mysql $singledb < $tmppath/mysql/$singledb.sql") == 0 or die "Unable to restore $singledb: $!";
    system("rm -r $tmppath") == 0 or log_user("Failed to clean up tmpdir $tmppath: $!");
    log_user("Mysql databse $singledb restored successfully");
}
sub find_partition {
    $backupnum = $1 if ($homedir =~ m%/home(\d*)/% );
    if (`/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{
                    list_backups($user);
                    print "Unable to determine correct /backup partition for $user. It appears the account is on multiple /backup partitions\n";
                    print "Please choose a partition manually from the available backups above with the --partition or -p flag.\n";
                    exit;
                }
            }
        }
    }
    return $backupnum;
}

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] [--partition|-p=(backup number)]  [--ip=(y|n|custom IP)] --home --full [--domain=(domainname)] [--path=(folder path)] [--backupname=(case number)] --backup [--rsyncargs=(extra rsync args)] [--restoreargs=(extra restoreacct args)] [--singledb=(Mysql db name)]

\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--account\tRestore the cpanel account
\t--home\t\tRestore the homedir
\t--full\t\tRestore the cpanel account and homedir
\t--domain\tRestore only the files for a domain and its subfolders
\t--path\t\tRestore only the files on a relative subpath within the users homedir
\t--backup|-b\tMake a backup of the things getting restored before restoring
\t--backupname\tOptional title to attach a case number to a backup
\t--rsyncargs\tPass extra args to the homedir rsync
\t--restoreargs\tPass extra args to the restoreacct
\t--singledb\tRestore a single mysql database

    };
}

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

