#!/usr/bin/env perl
# Backup CPanel related files for account restores

use strict;
use POSIX qw(WNOHANG _exit);
use Fcntl qw(:flock);
use Proc::Daemon;
use YAML qw( LoadFile );
use Sys::Hostname;
Proc::Daemon::Init unless $ARGV[0] =~ m/nobackground/;
use Proc::PID::File;
exit if Proc::PID::File->running();

my $eig_backup_config = '/opt/eig_linux/etc/eig_backup.conf';
my $backup_server_config = '/opt/eig_linux/etc/backup_server_info.conf';
my $backupdir = "eig_backup_staging/dirs.files";
my $hostname = hostname();
my $logfile = "/var/log/eig_backup/backup_cpanel.log";

if ( -x "/opt/eig_linux/bin/backupstate" ) {
    system("/opt/eig_linux/bin//backupstate --submit");
}

open(LOG, ">>$logfile") || die "Can't open logfile: $logfile: \n";
print LOG localtime(time) . ": Starting cPanel backup\n";

if ( !-x "/scripts/cpbackup" ) {
    print LOG localtime(time) . ": /scripts/cpbackup doesn't exist.  Exiting\n";
    close LOG;
    die "/scripts/cpbackup doesn't exist\n";
}

# /etc/cpbackup.conf template
my $cpbackup = {
                 "BACKUP2"          => "yes",
                 "BACKUPACCTS"      => "no",
                 "BACKUPCHECK"      => "yes",
                 "BACKUPDAYS"       => "0,1,2,3,4,5,6",
                 "BACKUPDIR"        => "/backup",
                 "BACKUPENABLE"     => "yes",
                 "BACKUPFILES"      => "yes",
                 "BACKUPFTPDIR"     => "",
                 "BACKUPFTPHOST"    => "",
                 "BACKUPFTPPASS"    => "",
                 "BACKUPFTPPASSIVE" => "no",
                 "BACKUPFTPUSER"    => "",
                 "BACKUPINC"        => "yes",
                 "BACKUPINT"        => "daily",
                 "BACKUPLOGS"       => "no",
                 "BACKUPMOUNT"      => "no",
                 "BACKUPRETDAILY"   => "0",
                 "BACKUPRETMONTHLY" => "0",
                 "BACKUPRETWEEKLY"  => "0",
                 "BACKUPTYPE"       => "normal",
                 "DIEIFNOTMOUNTED"  => "no",
                 "GZIPRSYNCOPTS"    => "--rsyncable",
                 "MYSQLBACKUP"      => "accounts",
                 "PREBACKUP"        => "0"
               };

# Obtain all home\d+ mount points
my $mounts = {};
if (open(MOUNTS,"/proc/mounts")) {
  while (<MOUNTS>) {
    $mounts->{$1} = 1 if (/^.+\s+(\/home\d*)\s+/);
  }
  $mounts->{"/home"} = 1;
} else {
  print "/proc/mounts inaccessible.  Terminating...\n";
  exit(2);
}

# Create GRAVEYARD folder for reaper for multi-home partitions
foreach my $m (keys %{$mounts}) {
  unless (-e "$m/GRAVEYARD") {
    mkdir "$m/GRAVEYARD", 0755;
  } else {
    unless (-d _) {
      unlink("$m/GRAVEYARD");
      mkdir "$m/GRAVEYARD", 0755;
    }
  }
}

# Remove old cpbackup logs
if (opendir(CPBACKUPLOGS,"/usr/local/cpanel/logs/cpbackup")) {
  while (my $cpbackuplog = readdir(CPBACKUPLOGS)) {
    next if (($cpbackuplog =~ /^\.\.?$/) || (!-f "/usr/local/cpanel/logs/cpbackup/$cpbackuplog"));
    unlink("/usr/local/cpanel/logs/cpbackup/$cpbackuplog") if ((time - (stat("/usr/local/cpanel/logs/cpbackup/$cpbackuplog"))[9]) > 86400);
  }
}


my $dirsfilelocation = "";
# Process dirs/files
# Only generate dirs/files if they're older than 23 hours
  foreach my $m (sort keys %{$mounts}) {
    next if (($m eq "/home") && ((scalar keys %{$mounts}) > 1));

    system("mkdir -p $m/eig_backup_staging/dirs.files 2>&1 ; chmod 0700 $m/eig_backup_staging/dirs.files 2>&1");
    next unless -d "$m/eig_backup_staging/dirs.files/";
    $cpbackup->{BACKUPDIR} = "$m/eig_backup_staging/dirs.files";

    my $rotateok = 1;
    my @now = localtime(time());
    $dirsfilelocation = "$m/eig_backup_staging/dirs.files/cpbackup";

    system("touch -d jan1 /opt/eig_linux/data/backups/dirs.files.lastrun") unless(-e "/opt/eig_linux/data/backups/dirs.files.lastrun");
    unless((time - (stat("/opt/eig_linux/data/backups/dirs.files.lastrun"))[9]) < (60*60*20)){
      system("echo ".time." >/opt/eig_linux/data/backups/dirs.files.lastrun");
      #get time so we can rotate stuff properly
      if($now[6] == 6 && $rotateok == 1){ #XXX needs to equal 0 if it's truely a sunday
        #rotate out the 2 week old backup
        rotateweeklytoweekly2($m);
      }

      # Output cpbackup template
      if (open(CPBACKUP,"+</etc/cpbackup.conf")) {
        flock(CPBACKUP, LOCK_EX);
        foreach (keys %{$cpbackup}) {
          print CPBACKUP "$_ $cpbackup->{$_}\n";
        }
        close(CPBACKUP);
        # Initiate backup for dirs/files for daily
        print LOG localtime(time) . ": Running /scripts/cpbackup\n";
        system(qq{/scripts/cpbackup --force 1>/dev/null});
        sleep 10;
        open(CPBACKUP,"+</etc/cpbackup.conf");
        flock(CPBACKUP, LOCK_EX);
        seek(CPBACKUP, 0, 0);
        $cpbackup->{BACKUPDIR} = "$m/eig_backup_staging/dirs.files";
        foreach (keys %{$cpbackup}) {
          print CPBACKUP "$_ $cpbackup->{$_}\n";
        }
        truncate( CPBACKUP, tell CPBACKUP);
        flock(CPBACKUP, LOCK_UN);
        close(CPBACKUP);
        # Cpbackup double forks, so we need to monitor the pid file
        my $pid = "";
        if (open(PID,"/var/cpanel/backuprunning")) {
          $pid = <PID>;
          chomp($pid);
          # Monitor cpbackup PID until it completes
          $0 = "backup_cpanel waiting on cpbackup to complete";
          unless ($pid eq "") {
            sleep 5 while (kill 0, $pid);
          }
        }
        if ( -d "/opt/eig_linux/etc" ) {
          print localtime(time) . ": Backing up eig_linux settings\n";
          system("rsync", '-rlptDW', '--bwlimit=2000', "/opt/eig_linux/etc/.", $cpbackup->{BACKUPDIR} . "/cpbackup/daily/dirs/_opt_eig_linux_etc");
        }
        if ( -d "/etc/firewall" ) {
          print localtime(time) . ": Backing up /etc/firewall\n";
          system("rsync", '-rlptDW', '--bwlimit=2000', "/etc/firewall/.", $cpbackup->{BACKUPDIR} . "/cpbackup/daily/dirs/_etc_firewall");
        }
        if ( -d "/etc/httpd/modsecurity.d" ) {
          print localtime(time) . ": Backing up modsec whitelists\n";
          system("rsync", '-rlptDW', '--bwlimit=2000', "--include", "00_whitelist*", "--exclude", "*", "/etc/httpd/modsecurity.d/.", $cpbackup->{BACKUPDIR} . "/cpbackup/daily/dirs/_etc_httpd_modsecurityd");
        }
        # Move dirs/dirs to seed and update atime/mtime on successful backup
        if (($? == 0) || ($? == -1)) {
          utime(time, time, "$m/eig_backup_staging/dirs.files/cpbackup/daily/dirs");
          utime(time, time, "$m/eig_backup_staging/dirs.files/cpbackup/daily/files");
        }
        #rsync to remote SSH box
        ssh_rsync($m);
      }
    }
  last;  #we really only want to do the first backup mount until we can get a better system in place
  }

# Reset /etc/cpbackup.conf
print LOG localtime(time) . ": Resetting /etc/cpbackup.conf\n";
$cpbackup->{BACKUPDIR} = "/backup";
$cpbackup->{BACKUPINT} = "daily";
$cpbackup->{BACKUPFILES} = "yes";
$cpbackup->{BACKUPACCTS} = "no";
$cpbackup->{BACKUPENABLE} = "no";
system(qq{chattr -i /etc/cpbackup.conf});
if (open(CPBACKUP,">/etc/cpbackup.conf")) {
  foreach (keys %{$cpbackup}) {
    print CPBACKUP "$_ $cpbackup->{$_}\n";
  }
}

print LOG localtime(time) . ": Backup Complete\n";
close(LOG);

sub ssh_rsync { 
  my $mntpnt = shift;
  my %eig_backup_config;
  my $hgbackupdir = "/admin/hgbackupdir";
  open my $config, '<', $eig_backup_config
    or die "Unable to open EIG Backup config file $eig_backup_config for reading: $!";
  while (chomp($_ = <$config>)) {
      $eig_backup_config{$1} = $2 if /^([^=]+?)=(.+)$/
  }
  close $config;
  if ( $eig_backup_config{ssh_sync} ) {
    $backup_server_config = LoadFile( $backup_server_config ) or die "SSH rsync defined but unable to open backup server config file $backup_server_config for reading: $!";
  }
  die "No SSH host found in $backup_server_config to rsync to!\n" if ( !$backup_server_config->{backup_ip} );
  my $non_user_data_location = 1;
  $non_user_data_location = $1 if ( $eig_backup_config{'non_user_data_location'} =~ m/^\/home(\d*)$/ );

  #SSH rsync to backup box
  my $rsync = "/usr/bin/ionice -c2 -n6 $hgbackupdir/rsync3 --rsync-path=/usr/bin/rsync --out-format=': /%f%L' --timeout=480 -xav --sparse --partial --bwlimit=8000 -e 'ssh -q -i $hgbackupdir/backupkey -F $hgbackupdir/ssh_config' $mntpnt/$backupdir/ root\@$backup_server_config->{backup_ip}:/home/$hostname/backup$non_user_data_location/dirs.files";
  print LOG localtime(time) . ": rsync to run: $rsync\n";
  my $output = `$rsync`;
  print LOG localtime(time) . ": \n$output";
  print LOG localtime(time) . ": Rotating backups on remote\n";
  my $location = $non_user_data_location;
  $location = 'empty' if ( $non_user_data_location eq '' );
  my $rotate = "ssh -i $hgbackupdir/backupkey -F $hgbackupdir/ssh_config root\@$backup_server_config->{backup_ip} '/opt/eig_linux/bin/rotate-cpanel-backups $hostname $location' ";
  $output = `$rotate`;
  print LOG localtime(time) . ": \n$output";


  if ($eig_backup_config{'dr_enabled'}){
    my $os_pattern = "/opt/eig_linux/etc/os_pattern";
    if ( ! -f "/opt/eig_linux/etc/os_pattern" ) {
      print LOG localtime(time) . ": Missing OS pattern ( $os_pattern ) file";
    } else {
      #my $rotate = "ssh -i $hgbackupdir/backupkey -F $hgbackupdir/ssh_config root\@$backup_server_config->{backup_ip} 'mkdir -p /home/$hostname/backup$non_user_data_location/server_files/ /home/$hostname/backup$non_user_data_location/server_files/OS ; chmod 700 /home/$hostname/backup$non_user_data_location/server_files' ";
      #$output = `$rotate`;
      #print LOG localtime(time) . ": \n$output";


      #unmount if mounted
      my $remote_command = "ssh -i $hgbackupdir/backupkey -F $hgbackupdir/ssh_config root\@$backup_server_config->{backup_ip} 'perl /dr/do_dr_mount.pl $hostname --unmount > /dev/null ; echo \$?' ";
      print LOG localtime(time) . ": DR_OS :: Command: $remote_command\n";
      chomp(my $commandret = `$remote_command`);

      print LOG localtime(time) . ": DR_OS :: Command_retval: $commandret\n";


      if ( $commandret =~ /^0/ ) {
        #mount
        $remote_command = "ssh -i $hgbackupdir/backupkey -F $hgbackupdir/ssh_config root\@$backup_server_config->{backup_ip} 'perl /dr/do_dr_mount.pl $hostname --mount > /dev/null ; echo \$?' ";
        print LOG localtime(time) . ": DR_OS :: Command: $remote_command\n";

        chomp($commandret = `$remote_command`);
        print LOG localtime(time) . ": DR_OS :: Command_retval: $commandret\n";
      }

      if ( $commandret =~ /^0/ ) {
        #rsync
        my $rsync = "/usr/bin/ionice -c2 -n6 $hgbackupdir/rsync3 --exclude-from=$os_pattern --include=/var/log/legacy --include=/var/log/domlogs --include=/var/log/httpd --exclude=/var/log/legacy/* --exclude=/var/log/domlogs/* --exclude=/var/log/httpd/* --rsync-path=/usr/bin/rsync --out-format=': /%f%L' --timeout=480 -xav --delete --sparse --partial --bwlimit=8000999 -e 'ssh -q -i $hgbackupdir/backupkey -F $hgbackupdir/ssh_config' / root\@$backup_server_config->{backup_ip}:/dr_mounts/$hostname/";

        print LOG localtime(time) . ": DR_OS :: Rsync: $rsync\n";

        my $output = `$rsync`;
        print LOG localtime(time) . ": \n$output";

        #mount
        $remote_command = "ssh -i $hgbackupdir/backupkey -F $hgbackupdir/ssh_config root\@$backup_server_config->{backup_ip} 'perl /dr/do_dr_mount.pl $hostname --postconf > /dev/null ; echo \$?' ";
        print LOG localtime(time) . ": DR_OS :: Command: $remote_command\n";

        chomp($commandret = `$remote_command`);
        print LOG localtime(time) . ": DR_OS :: Command_retval: $commandret\n";


        #unmount
        $remote_command = "ssh -i $hgbackupdir/backupkey -F $hgbackupdir/ssh_config root\@$backup_server_config->{backup_ip} 'perl /dr/do_dr_mount.pl $hostname --unmount > /dev/null ; echo \$?' ";
        print LOG localtime(time) . ": DR_OS :: Command: $remote_command\n";

        chomp($commandret = `$remote_command`);
        print LOG localtime(time) . ": DR_OS :: Command_retval: $commandret\n";
      }
    }  
  }
}
