#!/usr/bin/perl

use strict;
use Fcntl qw(:flock);
use File::Slurp;

umask(007);
my $DEBUG = 0;
my $userdata = {};

my $datadir = "/opt/eig_linux/data/backups";
my $loglocation = "/var/log/postbackup.log";

loaduserdata(\$userdata);
my $user = $ARGV[0];
my $srcdir = $ARGV[1];
my $dstdir = $ARGV[2];
my $btype = $ARGV[3];

unless($ARGV[3]){ #legacy way of getting called
  $user = (split('/', $ARGV[0]))[2];
  $srcdir = $ARGV[0];
  $dstdir = $ARGV[1];
  $btype = $ARGV[2];
}
my @dst = split('/', $dstdir);
my $bmnt = "/".$dst[1];



if($user eq ""){
  logger("user was empty, our arguments: ".join(' ',@ARGV));
  exit;
}

logger("$bmnt $user starting");

chmod( 0600, $loglocation);
chown( 0, 0, $loglocation);

#ignore rotate if our user smells funny
unless( $user =~ m/^[a-z0-9\.\-\_]*$/i){
  logger("$bmnt $user smells funny");
  exit;
}

#run pkgacct if needed
if($userdata->{$user}->{homedir} eq $srcdir){
  if($userdata->{$user}->{iscpaneluser}){
    backupuser($user, \$userdata, $bmnt);
    unlink("$datadir/$user.inprogress") if( -f "$datadir/$user.inprogress");
  }
}

logger("$bmnt $user complete");

##################################################################
##################################################################

#  only subs below this line

##################################################################
##################################################################

sub logger {
  my $message = shift;
  chomp($message);
  my $entry = localtime(time())." $message\n";
  open(LOG, ">>$loglocation");
  flock(LOG, 2);#
  print LOG $entry;
  close(LOG);
}

sub backupuser {
  my $username = shift;
  my $data_ref = shift;
  my $bmnt = shift;

  logger("$bmnt $user gonna run pkgacct");

  $ENV{'pkgacct-cpbackup'} = 1;
  $ENV{'pkgacct-logs'} = 'no';
  $ENV{'pkgacct-mysql'} = 'yes';
  $ENV{'pkgacct-psql'} = 'yes';
  $ENV{'INCBACKUP'} = 1;

  toucher("$datadir/$username.lock") unless (-e "$datadir/$username.lock");
  open(LOCKER, "<$datadir/$username.lock") or die("unable to open lock");
  unless (flock(LOCKER, LOCK_EX | LOCK_NB)) {
    logger("$username already being backed up");
    return;
  }

  #find out where we are going to backup the user
  my $backuptodir = $bmnt."/eig_backup_staging";

  #make sure symlink in /backup points where we want it to (if we should be in a different folder
#TODO: move to backuphelper or other script
#  if($bmnt ne "/backup"){
#    foreach my $type ( qw{ daily weekly monthly } ){
#      if(-l "/backup/cpbackup/$type/$username" ){
#        my $symdest = readlink("/backup/cpbackup/$type/$username");
#        if($symdest ne $bmnt."/cpbackup/$type/$username"){
#          unlink "/backup/cpbackup/$type/$username";
#          symlink($bmnt."/cpbackup/$type/$username", "/backup/cpbackup/$type/$username");
#        }
#      }else{
#        symlink($bmnt."/cpbackup/$type/$username", "/backup/cpbackup/$type/$username") unless -e "/backup/cpbackup/$type/$username";
#      }
#    }
#  }
  mkdir($backuptodir) unless(-e "$backuptodir/");
  chmod( 0711, "$backuptodir/");
  mkdir("$backuptodir/$username") unless(-e "$backuptodir/$username");
  chmod( 0750, "$backuptodir/$username");
  mkdir( $bmnt."/GRAVEYARD/") unless -e $bmnt."/GRAVEYARD/";
  chmod( 0700, $bmnt."/GRAVEYARD/");
  #move stuff out of the way so we don't let pkgacct update the hardlinked files:
  foreach my $ent (qw{ mysql mysql.sql mysql-timestamps psgl psql_grants.sql psql_users.sql addons dnszones homedir_paths meta nobodyfiles quota resellerconfig sds sds2 shadow shell ssldomain version }){
    rename("$backuptodir/$username/$ent", $bmnt."/GRAVEYARD/$ent.$username.$$" ) if ( -e "$backuptodir/$username/$ent");
  }
  foreach my $dir(qw{ userdata mysql cron meta fp vad vf sslkeys suspendedinfo interchange va bandwidth mm sslcerts httpfiles suspended mma logs psql counters cp resellerconfig dnszones mms homedir}){
    mkdir("$backuptodir/$username/$dir") unless -e "$backuptodir/$username/$dir";
  }
  #rotate old pkgacct logs
  unlink("$datadir/$username.1") if -e "$datadir/$username.1";    
  rename("$datadir/$username", "$datadir/$username.1") if -e "$datadir/$username";

  open(LOGFILE, ">$datadir/$username");
  print LOGFILE "".((stat("$datadir/$username.inprogress"))[9])." backupmgr started work on this user\n";
  close(LOGFILE);
  runcmd("timeout --signal=SIGKILL 3h /scripts/pkgacct --skiphomedir $username $backuptodir backup 2>&1 |/opt/eig_linux/bin/prefixtime >>$datadir/$username");
  unlink("$backuptodir/$username/lastgenerated") if(-e "$backuptodir/$username/lastgenerated");
  toucher("$backuptodir/$username/lastgenerated");
  toucher("$datadir/$username");
  if ( !-d "/backup/lastgenerated" ) {
      system("mkdir -p /backup/lastgenerated");
  }
  toucher("/backup/lastgenerated/$username");

  #fix permissions
  if(my ($login,$pass,$uid,$gid) = getpwnam($username)){
    chown( 0, $gid, "$backuptodir/$username");
    fixperms("$backuptodir/$username", $username, $gid);
  }

  close(LOCKER);
  unlink("$datadir/$username.lock");
}

sub runcmd {
  my $cmd = shift;
  print "RUNNING $cmd\n" if $DEBUG;
  system($cmd);
}

sub fixperms {
  my $dir = shift;
  my $user = shift;
  my $gid = shift;
  return unless $dir =~ m#/home.?/eig_backup_staging/$user#; #failsafe in case we parse to someplace else on the partition
  opendir(DIR, $dir);
  my @ent = readdir(DIR);
  close(DIR);
  foreach my $e (sort @ent){
    next if substr($e, 0,1) eq ".";
    next if $e eq "homedir";
    my $file = $dir."/".$e;
    lstat($file);
    if(-l _){
      #do nothing
    }elsif(-f _){
      chmod( 0640, $file);
      chown( 0, $gid, $file);
    }elsif(-d _){
      chmod( 0750, $file);
      chown( 0, $gid, $file);
      fixperms($file,$user,$gid);
    }
  }
}


sub toucher {
  my $file = shift;
  unless( -e $file ){
    open(FILE, ">$file");
    close(FILE);
  }else{
    my $mtime = time;
    my $atime = $mtime;
    utime($atime, $mtime, $file);
  }
}

sub loaduserdata {
  my $data_ref = shift;
  open(PASSWD, "</etc/passwd");
  while(<PASSWD>){
    chomp;
    my @ent = split(':', $_);
    $$data_ref->{$ent[0]}->{username} = $ent[0];
    $$data_ref->{$ent[0]}->{homedir} = $ent[5];
    $$data_ref->{$ent[0]}->{iscpaneluser} = 1 if -e "/var/cpanel/users/".$ent[0];
  }
  close(PASSWD);
}
