#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long;
use Sys::Hostname;
use YAML qw( LoadFile Load );
use JSON::XS;
use Data::Dumper;

my $eig_backup_config_file = '/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 $restorelocaldata = 0;
my $compressed = 0;
my $zip = 0; 
my $password; 
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,
    "localdata"     => \$restorelocaldata,
    "compressed|c"  => \$compressed,
    "zip|z"         => \$zip,
    "password=s"      => \$password,
);
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 && !$compressed ));
$full = 1 if (!($restorehome||$restoreaccount||$domain||$subpath||$singledb||$restorelocaldata||$compressed));
$restoreargs .= ' --force';

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

die "Dirty user found '$user'" unless $user =~  /^[a-z0-9.-_]+$/;
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 = (defined $homedir && $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";
    }elsif ($restorelocaldata){
        print "Attempt to restore local.data from $type backup? [Y|n]\n";
    }elsif ($compressed){
        print "Attempt to provide a compressed $type backup? [Y|n]\n";
    } else {
        print "You shouldn't be here\n";
        exit;
    }
    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");
compressed_backup() if $compressed;
restore_db() if $singledb;
restore_account() if $restoreaccount || $full;
restore_home($subpath) if $restorehome || $full;
restore_localdata() if ($eig_backup_config{'cmh'} && ($restorelocaldata || $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");
    if ($eig_backup_config{'cmh'} && !getpwnam($user)) {
        log_user("Creating Cpanel account");
        my $userdata = LoadFile("$tmppath/userdata/main");
        my $createacct = "whmapi1 createacct username=$user domain=$userdata->{'main_domain'} homedir=/home$backupnum/$user";
        system("$createacct") == 0 or log_user("Failed to create account for $user with command $createacct");
    }
    $restoreargs .= " --skipaccount" if getpwnam($user);
    $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_localdata{
    my $homedir = (getpwnam("$user"))[7] or die_user("failed to find passwd entry for $user");
    (my $localdata_home = $homedir) =~ s/home/local.data/;
    log_user("Restoring $localdata_home");
    my $cmd = qq(rsync -av -e "ssh -i $backupkey" $rsyncargs root\@$backup_server_config->{backup_ip}:/home/$hostname$srcpath/local.data/ $localdata_home/ 2>&1 >> $logdir/sshrestore.log);
    system("$cmd") == 0 or die_user("Unable to restore localdata");
    $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/$singledb.sql $tmppath/mysql/$singledb.sql 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/;
    if (! -d "/var/lib/mysql/$singledb"){
        log_user("Creating $singledb");
        system("uapi --user=$user Mysql create_database name=$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 compressed_backup{
    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("Compressing $type for $user");
    my $path_string = $subpath ? "_$subpath" : "";
    $path_string =~ s|/|_|g;
    my $tar_name = "$user\_$type$path_string.tar.gz";
    my $cmd;
    if ($zip) { 
        $password = defined $password ? "-P $password" : "";
        $tar_name = "$user\_$type$path_string.zip";
        $cmd = qq(ssh  -i $backupkey root\@$backup_server_config->{backup_ip} 'cd  /home/$hostname/backup$backupnum/$location/$type/ && zip -r $password /home/$hostname/backup$backupnum/$tar_name $user');
        print "$cmd\n";
    } else { 
        $cmd = qq(ssh  -i $backupkey root\@$backup_server_config->{backup_ip} 'tar -czvf /home/$hostname/backup$backupnum/$tar_name  -C /home/$hostname/backup$backupnum/$location/$type/ $user');
    }
    $cmd .= "/homedir/$subpath" if $subpath;
    system("$cmd") == 0 or die_user("Unable to tar files");
    $cmd = qq(rsync -av -e "ssh -i $backupkey" $rsyncargs root\@$backup_server_config->{backup_ip}:/home/$hostname/backup$backupnum/$tar_name $homedir/ 2>&1 >> $logdir/sshrestore.log);
    system("$cmd") == 0 or die_user("Unable to sync tar over");
    $cmd = qq(chown $user: $homedir/$tar_name);
    system("$cmd") == 0 or die_user("Unable to chown backup");
    $cmd = qq(ssh  -i $backupkey root\@$backup_server_config->{backup_ip} 'rm -fv /home/$hostname/backup$backupnum/$tar_name');
    system("$cmd") == 0 or die_user("Unable cleanup /home/$hostname/backup$backupnum/$tar_name on backup server");
    log_user("$homedir/$tar_name compressed successfully");
}
sub find_partition {
    my $data = ssh_command("/opt/eig_linux/bin/get_backup_dates --server $hostname --user $user");
    if (defined $homedir) {
        $backupnum = $1 if ($homedir =~ m%/home(\d*)/% );
        return $backupnum if defined $data->{$user}->{'backup-dates'}->{"/backup$backupnum"};
    }
    undef $backupnum;
    foreach my $backup_type (qw(cpbackup archived-backups)){
        last if defined $backupnum;
        $archived = 1 if $backup_type eq "archived-backups";
        foreach my $partition (keys %{$data->{$user}->{'backup-dates'}}){
            last if defined $backupnum;
            foreach my $backup_interval (qw(daily weekly monthly bimonthly)){
                next unless defined $data->{$user}->{'backup-dates'}->{$partition}->{$backup_type}->{$backup_interval};
                $backupnum = $1 if ($partition =~ m%/backup(\d*)$% );
                last;
            }
        }
    }
    if (! defined $backupnum) {
       print "No backups found for $user!\n";
       exit;
    }
    return $backupnum;
}

sub list_backups {
    my $user = shift;
    my $archived_only = 0;
    my $data = ssh_command("/opt/eig_linux/bin/get_backup_dates --server $hostname --user $user");
    if ( not defined $data->{$user} ) {
        print "No backups found for $user!\n";
        exit;
    }
    print "\nBackups available:\n";
    foreach my $partition (keys %{$data->{$user}->{'backup-dates'}}){
    foreach my $backup_type (keys %{$data->{$user}->{'backup-dates'}->{$partition}}){
        foreach my $backup_interval (keys %{$data->{$user}->{'backup-dates'}->{$partition}->{$backup_type}}){
            print "$partition/$backup_type/$backup_interval/$user: " . localtime($data->{$user}->{'backup-dates'}->{$partition}->{$backup_type}->{$backup_interval}) . "\n";
            }
        }
    }
}

sub usage {
    print qq{$0 usage:
\t$0 --user|-u=<user> --type|-t=<daily|weekly|monthly|bimonthly> [--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|bimonthly)
\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
\t--compressed\tCopy a compressed backup to the customer's homedir
\t--zip\t\tUse with --compressed flag to create zip instad of tar
\t--password=\tUse with --zip to create password protected zip 
    };
}

sub load_config {
  open(DC, "<$eig_backup_config_file")
    or die "Unable to open EIG Backup config file $eig_backup_config_file 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_command{
    my $command = shift;
    my $cmd="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} $command";
    my $stdout = qx($cmd);
    my $data=eval { decode_json($stdout) } || {};
    return $data;
}
