#!/usr/bin/perl

use strict;
use Sys::Hostname;
use File::Path qw(rmtree make_path);
use YAML qw( LoadFile );
use Proc::PID::File;
exit if Proc::PID::File->running();

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

my @dbs = qw( horde mysql roundcube phpmyadmin );
my $backupdir = "eig_backup_staging/non-user-mysql";
my $backupdirmode = oct("0700");
my $lastrun = "/opt/eig_linux/data/backups/backupmysql.lastrun";
my $minimumrunperiod = 60*60*20;
my $mysqldumpoptions = '-c -Q -q';
my $mysqldumpesmode = oct("0600");
my $DEBUG = 1;
my $log_file = "/var/log/eig_backup/non-user-mysql.log";
my $hostname = hostname();
my $eig_backup_config = '/opt/eig_linux/etc/eig_backup.conf';
my $backup_server_config = '/opt/eig_linux/etc/backup_server_info.conf';
my $hgbackupdir = "/admin/hgbackupdir";

my @homedirs;

#open log file
open(LOG, ">>$log_file") or die "Can't open log file:$@\n";
#only run if we haven't run recently
if((time - (stat($lastrun))[9]) < $minimumrunperiod) {
    print LOG "Lastrun too recent, exiting\n";
    exit;
}

#Load Datacycle configs
my %eig_backup_config;
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*)$/ );

#locate where we will do backups
open (MNT, "</proc/mounts");
while (<MNT>) {
  my @tmp = split (/\s/,$_);
  next unless ($tmp[1] =~ m%/home%);
  next if ($tmp[1] =~ m%/home\d*/virtfs/%);
  push @homedirs, $tmp[1];
}
close MNT;
push @homedirs, "/home" if ( scalar(@homedirs) < 1 );

my $mntpnt = "";
my $target_exists = 0;
foreach my $pnt (sort @homedirs ){
  $target_exists = 1 if ( $pnt =~ m/^\/home$non_user_data_location$/ );
  next unless -e "$pnt/$backupdir";
  $mntpnt = $pnt;
}
if( $mntpnt eq "" && $target_exists ){
  $mntpnt = "/home$non_user_data_location";
  make_path("$mntpnt/$backupdir", {mode => $backupdirmode}) or die "Failed to create path $mntpnt/$backupdir: $@\n";
} elsif( $mntpnt eq ""){
  print LOG "no suitable mntpoint found\n";
  exit;
}

#make sure the permissions on that file are strict
chmod $backupdirmode, "$mntpnt/$backupdir";

#dump each database
foreach(@dbs){
  print LOG "dumping $_...\n";
  my $cmd = "HOME=/root /usr/bin/mysqldump $mysqldumpoptions $_ >$mntpnt/$backupdir/$_.inprogress.sql";
  print LOG "$cmd\n" if $DEBUG;
  system($cmd);
  print LOG "done\n";
  rename("$mntpnt/$backupdir/$_.inprogress.sql", "$mntpnt/$backupdir/$_.0.sql");
  chmod $mysqldumpesmode, "$mntpnt/$backupdir/$_.0.sql";
}

#SSH rsync to backup box
my $rsync = "/usr/bin/ionice -c2 -n6 $hgbackupdir/rsync3 --rsync-path=/home/hgbackupdir/rsync3 --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/non-user-mysql";

print LOG "Starting SSH rsync...\n";
print LOG $rsync . "\n" if $DEBUG;
system("$rsync >> $log_file") == 0 or print LOG "Failed to rsync to $backup_server_config->{backup_ip}: $@\n";
print LOG "Complete\n";

#Remove staging folder
print LOG "Removing temporary $mntpnt/$backupdir/\n";
if ( "$mntpnt/$backupdir/" =~ m/^\/home\d*\/eig_backup_staging\/non-user-mysql/ ) {
  system("rm -rf $mntpnt/$backupdir/");
} else {
  print LOG "Tempdir: $mntpnt/$backupdir/ is corrupt.  Refusing to remove\n";
}

#Rotate mysql dumps on backup box
my $ssh = "ssh -q -i $hgbackupdir/backupkey -F $hgbackupdir/ssh_config root\@$backup_server_config->{backup_ip} '/opt/eig_linux/bin/rotate-non-user-mysql $hostname /backup$non_user_data_location'";
my $ssh_out = `$ssh`;
print LOG $ssh_out;
die "$!" if $?;

#touch mysql-backup.lastrun-date file
system("/bin/touch","$lastrun");
