#!/usr/bin/perl
use strict;
use warnings;
use Getopt::Long;
use Proc::PID::File;
use FindBin qw($Bin);
use lib "$Bin/../lib";
use lib '/opt/eig_linux/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 $opts = {
    cleanup => 0,
    run => 0,
    list => 0,
};

usage() if (!GetOptions(\%{$opts},
    "server|s=s",
    "cleanup|c",
    "list|l",
    "help|h",
));
usage() if($opts->{'help'});

my $is_zfs = $bk->get_config_value('type') =~ m/zfs/ ? 1 : 0;

my $active_partitions = get_partitions();
my $clients = $bk->get_clients();
my $bad_partitions = find_bad_partitions($active_partitions, $clients);

if ($opts->{list}){
    print "The following partitions don't appear to be in use and can be cleaned up:\n";
    print join ("\n", @$bad_partitions);
    print "\n";
}
clean_bad_partitions($bad_partitions) if $opts->{cleanup};

sub get_partitions {
    my @active;
    if ($is_zfs) {
        foreach my $line (qx(/usr/sbin/zfs list -H -oname | cut -d/ -f2)){
            next if $line =~ m/backup/;
            chomp($line);
            push @active, $line;
        }
    } else {
        foreach my $line (qx(lvs backup --units T --noheadings | awk '{print \$1}')){
            chomp($line);
            push @active, $line;
        }
    }
    return \@active;
}

sub find_bad_partitions {
    my ($active,$clients) = @_;
    my @bad;
    PARTLOOP: foreach my $part (@$active){
        foreach my $client (keys %$clients){
            foreach my $cpart (@{$clients->{$client}->{partitions}}){
                next PARTLOOP if $cpart->{plabel} eq $part;
                #Short hostname check
                my $short = (split '\.', $client)[0];
                next PARTLOOP if $part =~ m/$short/;
            }
        }
        if ($opts->{server}){
            my $short = (split '\.', $opts->{server})[0];
            next unless $part =~ m/$short[a-z0-9]{0,2}\./;
        }
        push @bad, $part;
    }
    return \@bad;
}

sub clean_bad_partitions {
    my $bad = shift;
    if (!$is_zfs){
        # Clean Exports
        my $changed = 0;
        my $out;
        open( my $fh, '<', '/etc/exports');
        while ( my $line = <$fh> ){
            $line =~ m|/home/([^\/\s]+)|;
            if (defined $clients->{$1}){
                $out .= $line;
            } else {
                $changed = 1;
                chomp($line);
                print "Removing '$line' from /etc/exports\n";
            }
        }
        close $fh;
        if ($changed) {
            open ($fh, '>', '/etc/exports');
            print $fh $out;
            close $fh;
            system("exportfs -ra");
        }

        # Clean /etc/fstab
        $changed = 0;
        $out = "";;
        open($fh, '<', '/etc/fstab');
        while ( my $line = <$fh> ){
            if ($line =~ m|\s(/home/([^\/\s]+)/backup\d?)|){
                if (defined $clients->{$2}){
                    $out .= $line;
                } else {
                    $changed = 1;
                    chomp($line);
                    print "Removing '$line' from /etc/fstab and unmounting $1\n";
                    system("umount $1");
                }
            } else {
                $out .= $line;
            }
        }
        close $fh;
        if ($changed) {
            open ($fh, '>', '/etc/fstab');
            print $fh $out;
            close $fh;
        }
    }

    # Clean partitons
    foreach my $part (@$bad){
        if ($is_zfs){
            print "Removing ZFS Slice: $part\n";
            system("zfs destroy backup/$part");
        } else {
            print "Removing LV: $part\n";
            system("umount -v /dev/mapper/backup-$part");
            system("lvremove -f backup/$part");
        }
    }
}
