#!/usr/bin/env perl

use strict;
use Fcntl qw(:flock);
use File::Slurp;
use Getopt::Long;
use File::Path;
use JSON;
use FindBin qw($Bin);
use lib "$Bin/../lib";
use lib "/opt/eig_linux/lib";
use BackupServer;

my $bk = new BackupServer;

umask(007);
my $DEBUG = 0;

my ($host,$partition,$user,$btype);
GetOptions ("host=s"            => \$host,
            "partition=s"       => \$partition,
            "user=s"            => \$user,
            "type=s"            => \$btype),
  or die("Error in command line arguments\n");
my $bmnt = "/home/$host/$partition";
die "Invalid partition $partition for $host\n" if ( !-d $bmnt);
die "Invalid type $btype\n" if ( $btype !~ m/(full|incremental)/ );

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

$bk->logger('notice',"$bmnt $user starting");
my $starttime = time();

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

# figure out what rsync option to use
my $rsynccmd = find_rsync();

my $stats = {};
fixperms($bmnt,$user);

my $midtime = time();
$stats->{time_fixperms} = $midtime - $starttime;

rotate($bmnt,$user,$btype);

my $endtime = time();
$stats->{time_rotate} = $endtime - $midtime;
$stats->{time_total} = $endtime - $starttime;
save_stats($stats,$host,$partition,$user);

$bk->logger('notice',"$bmnt $user complete");

#########
# Subs
#########
sub save_stats {
  my $data = shift;
  my $host = shift;
  my $partition = shift;
  my $user = shift;
  my $bmnt = "/home/$host/$partition";
  my $statedir = "/opt/eig_linux/state/$host";
  File::Path::make_path("$statedir");
  foreach my $btype (qw{ daily weekly monthly olddaily expired }){
    my @lg = stat("$bmnt/cpbackup/$btype/$user/lastgenerated");
    $data->{lastgenerated}->{$btype} = $lg[9] if (@lg);
    my @bc = stat("$bmnt/cpbackup/$btype/$user/homedir/.cpanel/backup_check");
    $data->{backup_check}->{$btype} = $bc[9] if (@bc);
  }
  my $json = encode_json($data);
  write_file("$statedir/$user.json",$json);
}

sub fixperms {
  my $bmnt = shift;
  my $username = shift;

  $bk->logger('notice',"$bmnt $user gonna fixperms");

  my $uid;
  if ( -d "$bmnt/cpbackup/seed/$user" ) {
    $uid = (stat("$bmnt/cpbackup/seed/$user"))[5];
  } else {
    $bk->logger('error',"failed to determin UID for $user from $bmnt/cpbackup/seed/$user");
    return;
  }

  if ( -d "$bmnt/cpbackup/seed/$user/homedir" ) {
    $bk->logger('notice',"setting $bmnt/cpbackup/seed/$user/homedir ownership to UID: $uid");
    chown 0, $uid, "$bmnt/cpbackup/seed/$user/homedir";
    chmod 0750, "$bmnt/cpbackup/seed/$user/homedir";
  } else {
    $bk->logger('notice',"homedir does not exist for $user");
  }
  return;
}

sub rotate {

  my $bmnt = shift;
  my $username = shift;
  my $btype = shift;

  $bk->logger('notice',"$bmnt $user gonna rotate");

  #make sure folders exist for each backup
  foreach my $btype (qw{ daily weekly monthly olddaily expired }){
    if( ! -e $bmnt."/cpbackup/$btype"){
      mkdir($bmnt."/cpbackup/$btype");
      chmod(0711,$bmnt."/cpbackup/$btype");
    }
  }
 
  #do we have a half-rotated folder sitting around?
  if( -d $bmnt."/cpbackup/olddaily/$username" ){
    rename($bmnt."/cpbackup/olddaily/$username", $bmnt."/GRAVEYARD/olddaily.$username.$$");
    $bk->logger('notice', "olddaily for $bmnt $username existed, moving to graveyard\n");
  }

  #move daily to olddaily
  unlink $bmnt."/cpbackup/daily/$username" if( -l $bmnt."/cpbackup/daily/$username");
  if(-d _ ){
    rename( $bmnt."/cpbackup/daily/$username" , $bmnt."/cpbackup/olddaily/$username");
    $bk->logger('notice',"$bmnt $username rename daily to olddaily\n");
  }

  #move seed to daily
  rename( $bmnt."/cpbackup/seed/$username", $bmnt."/cpbackup/daily/$username");
  $bk->logger('notice',"$bmnt $username rename seed to daily\n");
  #horay, customers now see their new backup

  my @lt = localtime();
  #if it's saturday or sunday
  my $weeklyage = int((time() - (lstat($bmnt."/cpbackup/weekly/$username/lastgenerated"))[9]) / 86400);
  my $monthlyage = int((time() - (lstat($bmnt."/cpbackup/monthly/$username/lastgenerated"))[9]) / 86400);

  if($lt[6] == 6 or $lt[6] == 0 or $monthlyage > 29 or $weeklyage > 10){
    if($monthlyage > 27 and $weeklyage > 6){
      rename($bmnt."/cpbackup/monthly/$username", $bmnt."/cpbackup/expired/$username");
      $btype = "full";
      $bk->logger('notice',"$bmnt $username expire monthly");
    }elsif($weeklyage > 7){
      rename($bmnt."/cpbackup/weekly/$username", $bmnt."/cpbackup/expired/$username");
      $btype = "full";
      $bk->logger('notice',"$bmnt $username expire weekly");
    }
  }

  #if we don't have a monthly
  if( ! -d $bmnt."/cpbackup/monthly/$username" and -e $bmnt."/cpbackup/weekly/$username"){
    unlink $bmnt."/cpbackup/monthly/$username" if( -l $bmnt."/cpbackup/monthly/$username");
    rename( $bmnt."/cpbackup/weekly/$username", $bmnt."/cpbackup/monthly/$username");
    $bk->logger('notice',"$bmnt $username promote weekly");
  }
  #if we don't have a weekly
  if( ! -d $bmnt."/cpbackup/weekly/$username" and -e $bmnt."/cpbackup/olddaily/$username"){
    unlink $bmnt."/cpbackup/weekly/$username" if( -l $bmnt."/cpbackup/weekly/$username");
    rename( $bmnt."/cpbackup/olddaily/$username", $bmnt."/cpbackup/weekly/$username");
    $bk->logger('notice',"$bmnt $username promote olddaily");
  }
  if( ! -d $bmnt."/cpbackup/olddaily/$username"){
    if( -d $bmnt."/cpbackup/expired/$username"){
      rename($bmnt."/cpbackup/expired/$username", $bmnt."/cpbackup/olddaily/$username");
      $bk->logger('notice',"$bmnt $username reclaim expired as olddaily to lessen writes");
    }
  }
  if( ! -d $bmnt."/cpbackup/olddaily/$username"){
    #we get to hardlink everything from daily to seed
    $bk->logger('notice',"$bmnt $username recreate seed as olddaily didn't exist");
  }else{
    #we get to use our magic script to gracefully sync daily back to seed
    rename( $bmnt."/cpbackup/olddaily/$username", $bmnt."/cpbackup/seed/$username");
    $bk->logger('notice',"$bmnt $username rename olddaily as seed. btype: $btype");
  }
  if($rsynccmd){
    #### rsync -rlptgoHxS --delete --link-dest=/home/rock256.eigdev.com/backup1/cpbackup/daily/ /home/rock256.eigdev.com/backup1/cpbackup/daily/tqjshsix /home/rock256.eigdev.com/backup1/cpbackup/seed/
    runcmd("$rsynccmd -rlptgoHxS --delete --link-dest=$bmnt/cpbackup/daily/ $bmnt/cpbackup/daily/$username $bmnt/cpbackup/seed/");
  }else{
    runcmd("/usr/bin/ionice -c2 -n6 /opt/eig_linux/bin/hardlinker --host=$host --partition=$partition --user=$user --type=daily");
  }
}

sub find_rsync {
  my @rsyncs = qw( /opt/eig_linux/bin/rsync3 /bin/rsync /usr/bin/rsync );
  foreach my $rsync (@rsyncs){
    next if ! -e $rsync;
    #print "checking $rsync\n";
    my $ver = qx($rsync --version |grep ' version ' |awk '{print \$3}');
    chomp($ver);
    if($ver eq '3.1.2'){
      return $rsync;
    }
  }
  return;
}

sub runcmd {
  my $cmd = shift;
  $bk->logger('notice',"$bmnt $user CMD: $cmd");
  print "RUNNING $cmd\n" if $DEBUG;
  system($cmd);
}
