#!/usr/bin/perl
use strict;

use YAML qw( LoadFile );
use Data::Dumper;
use Proc::PID::File;
if (Proc::PID::File->running()){
  print "I am already running!\n";
  exit();
}

use FindBin qw($Bin);
use lib "$Bin/../lib";
use lib "/opt/eig_linux/lib";
use BackupServer;
my $bk = new BackupServer;

my $DEBUG = 0;
my $archivedir = "archived-backups";
my $daystokeep = $bk->get_config_value('archiver_days');
$daystokeep = 60 if ! defined($daystokeep);

my $now = time;

my $bmounts = {};
my $hmounts = {};
my $userdata;
my %ignorables = qw(
    GRAVEYARD 1
    MoveSite  1
    dirs  1
    files   1
    lost+found  1
    cpbackup 1
);

my @backuptypes = qw{ daily weekly monthly };
if(isbackupidle()){
  push( @backuptypes, "seed");
}


getbackupmounts(\$bmounts,\$hmounts);

my $host;
my $part;

#go through each backup mount
foreach my $m (sort keys %{$bmounts}){
  print "\nchecking mount $m\n" if $DEBUG;
  if ( $m =~ m/^\/home\/(.*)\/backup(\d*)$/ ) {
      $host = $1;
      $part = $2;
      if ( ( $part == 1 || $part eq '' ) && -f "$m/dirs.files/cpbackup/daily/active_users" ) {
        if ( -M "$m/dirs.files/cpbackup/daily/active_users" > 3 ) {
          $bk->logger('notice', "active user file too old, skipping");
          next;
        } else {
          $userdata->{$host} = LoadFile("$m/dirs.files/cpbackup/daily/active_users");
          print "Found data file for $host\n" if $DEBUG;
        }
      } else {
        if ( $userdata->{$host} ) {
          print "Userdata already loaded for $host\n" if $DEBUG;
        } else {
          $bk->logger('notice',"Cannot find userdata for backup$part on $host, skipping");
          next;
        }
     }
  } else {
     next;
  }

  #daily weekly monthly etc
  foreach my $type (@backuptypes){
    my $dirtocheck = "/cpbackup/$type";
    next if (defined($bmounts->{"$m/$dirtocheck"}));
    print "\nchecking dir $m$dirtocheck\n" if $DEBUG;
    opendir(DIR, "$m$dirtocheck");
    my @dir = readdir(DIR);
    close(DIR);
    #each user in that directory
    ENTRY: foreach my $entry (@dir){
      next if ( $ignorables{$entry} == 1);
      next if ( $entry eq $archivedir);
      next if ( substr($entry, 0, 1) eq ".");
      next if ( -l "$m$dirtocheck/$entry");
      if ( $userdata->{$host}->{$part}->{$entry} ) {
        print "found active user $entry\n" if $DEBUG;
        next; 
      }
      $bk->logger('notice', "!!! User: $entry not found to be active !!!");
      my @attrib = stat("$m$dirtocheck/$entry");
      if($attrib[9] > (time() - 7200)){
        $bk->logger('notice', "not old enough to delete!");
        next ENTRY;
      }
      mkdirifneeded("$m/$archivedir");
      mkdirifneeded("$m/$archivedir/$type");
      rotate_dir("$m/$archivedir/$type/$entry");
      $bk->logger("Archiving $m$dirtocheck/$entry");
      rename("$m$dirtocheck/$entry","$m/$archivedir/$type/$entry") or warn "unable to rename $m$dirtocheck/$entry $m/$archivedir/$type/$entry $!";
      utime $now, $now, "$m/$archivedir/$type/$entry" or warn "unable to update timestamp on $m/$archivedir/$type/$entry $!";
    }
  }
}

my $oldlimit = time() - ($daystokeep * 24 * 60 * 60);
foreach my $m (sort keys %{$bmounts}){
  next unless -e "$m/$archivedir";
  print "\n\ncleaning old stuff from $m/$archivedir\n" if $DEBUG;
  foreach my $type (@backuptypes){
    next unless -d "$m/$archivedir/$type";
    opendir(ADIR, "$m/$archivedir/$type");
    my @entries = readdir(ADIR);
    close(ADIR);
    foreach my $entry (@entries){
      next if($ignorables{$entry} == 1);
      next if(substr($entry, 0, 1) eq ".");
      my @attrib = stat("$m/$archivedir/$type/$entry");
      if($attrib[9] < $oldlimit){
        print "nuking: $entry\n" if $DEBUG;
#        mkdir "$m/GRAVEYARD", 0700 unless(-e "$m/GRAVEYARD") or warn "unable to mkdir $m/GRAVEYARD $!";
        if (! -e "$m/GRAVEYARD"){
          mkdir "$m/GRAVEYARD", 0700 or warn "unable to mkdir $m/GRAVEYARD $!";
        }
        $bk->logger("Moving $m/$archivedir/$type/$entry to GRAVEYARD");
        rename("$m/$archivedir/$type/$entry", "$m/GRAVEYARD/$entry.$$") or warn "unable to rename $m/$archivedir/$type/$entry $m/GRAVEYARD/$entry.$$ $!";
      }
    }
  }
}



sub mkdirifneeded {
  my $dir = shift;
  return if -e $dir;
  mkdir($dir, 0755) or warn "unable to mkdir $dir $!";
}

sub rotate_dir {
  my $dir = shift;
  return if ( !-e $dir );
  my $time = time();
  rename( "$dir", "$dir.$time" ) or warn "unable to rotate existing $dir to $dir.$time: $1\n";
}

sub isbackupidle {
  if(-e "/root/backup-stage"){
    my $status = `cat /root/backup-stage`;
    chomp($status);
    if($status == "1"){ #are we idle?
      return 1;
    }else{
      return 0;
    }
  }else{
    return 1;
  }
}


sub getbackupmounts {
  my $b_ref = shift;
  my $h_ref = shift;
  open(MOUNTS, "</proc/mounts");
  while(<MOUNTS>){
    my @parts = split('\s+', $_);
    if($parts[1] =~ m#^/home/.*/backup\d*#){
      $$b_ref->{$parts[1]} = $parts[0];
    }
  }
}
