#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use Proc::PID::File;
use FindBin qw($Bin);
use lib "$Bin/../lib";
use BackupServer;
use Data::Dumper;

my $bk = new BackupServer;
my $data = $bk->get_partitions();

if (Proc::PID::File->running()){
  print "We seem to be already runnning\n";
  exit();
}

my $run = 0;
my $cron = 0;
my $force = 0;
my $threshold = ".94";
my $wanted_percent = ".83";
my $reserve = 10;

GetOptions(
    "run"           => \$run,
    "threshold=f"   => \$threshold,
    "wanted=f"      => \$wanted_percent,
    "cron"          => \$cron,
    "force"         => \$force,
);

die "Threshold should be between .6 and .99!" if ($threshold < .6 || $threshold > .99);
die "Wanted should be between .4 and .95!" if ($wanted_percent < .4 || $wanted_percent > .95);

print "Checking for backups over $threshold and wanting to resize to $wanted_percent\n";

my $df;
for my $line ( qx(df -P) ){
    my ($device, $total, $used, $availble, $capacity, $mount) = split /\s++/, $line;
    $mount =~ m|/home/([^/]++)(/backup\d?)| or  next;
    my $hostname = $1;
    my $cmount = $2;
    my $plabel = $1 if $device =~ m|/dev/mapper/backup\-(\S+)|;
    my $usage = ($1/100) if ($capacity =~ m/(\d+)%/);
    if ($usage >= $threshold){
        $df->{$hostname}->{$cmount}->{'plabel'} = $plabel;
        $df->{$hostname}->{$cmount}->{'adjustment'} = sprintf "%.02f", ((($used/$wanted_percent) - $total)/1024/1024/1024 + .005);
        $df->{$hostname}->{$cmount}->{'total'} = sprintf "%.02f", (($used/$wanted_percent)/1024/1024/1024 + .005);
    }
}
#iterate through $data and  resize if we its called for
foreach my $part (keys %$data){
    next unless (defined $data->{$part}->{'chostname'} and defined $data->{$part}->{'cmount'});
    my $hostname = $data->{$part}->{'chostname'};
    my $cmount = $data->{$part}->{'cmount'};
    if (defined $df->{$hostname}->{$cmount}->{'adjustment'}){
        print "$data->{$part}->{'plabel'} needs an additional $df->{$hostname}->{$cmount}->{'adjustment'}\n";
        my $free = $1 if ( qx(vgs backup --noheadings -o vg_free --units t) =~ m/([0-9]+\.[0-9]+)t/);
        if ($free - $df->{$hostname}->{$cmount}->{'adjustment'} < $reserve){
        print "NOT ENOUGH SPACE MIGRAITON NEEDED!\n";
        next unless $force;
    }
        if ($data->{$part}->{'homesize'} * 1.5 <= $df->{$hostname}->{$cmount}->{'total'}){
            print "Resize greater then 1.5 home size\n";
            next unless $force;
        }
        resize_partition($hostname,$cmount) if $run;
     }
}
sub resize_partition{
    my $hostname = shift;
    my $cmount = shift;
    my @active = qx(ps auxwww | grep '$hostname/$cmount');
    if (@active > 2){
        print "Open procs found on $hostname!\n";
        print "Skipping...\n" if $run;
        return;
    }
    system ("echo 'y' | /opt/eig_linux/bin/resize_volume -p $df->{$hostname}->{$cmount}->{'plabel'} -s $df->{$hostname}->{$cmount}->{'adjustment'}");
}
