#!/usr/bin/env perl
use strict;
use Data::Dumper;

use FindBin qw($Bin);
use lib "$Bin/../lib";
use BackupCompute;

my $bc = new BackupCompute;

my $clients = $bc->get_clients();

my @exports;
open(my $fh, '<', "/etc/exports");
foreach my $line (<$fh>) {
    push @exports,$1 if $line =~ m|/images/(\S+)|;
}
close $fh;

my $needs_update = 0;
foreach my $client (keys %$clients){
    if (! grep {$client eq $_} @exports) {
        $needs_update = 1;
        $clients->{$client}->{'needsupdate'} = 1;
    }
}

if ($needs_update){
    open (my $fh, '>>', '/etc/exports');
    foreach my $client (keys %$clients){
        if ($clients->{$client}->{'needsupdate'}){
            mkdir "/images/$client" if (! -d "/images/$client");
            print $fh "/images/$client $clients->{$client}->{'backup_ip'}(rw,sync,no_root_squash)\n";
        }
    }
    system("exportfs -a") == 0 or die "Failed to export all: $!\n";
}
