#!/usr/bin/env perl
use strict;
use lib '/opt/eig_linux/lib';
use BackupCompute;

my $bc = new BackupCompute;

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

my $out;
open(my $fh, '<', "/etc/exports");
my $needs_update = 0;
foreach my $line (<$fh>) {
    if ($line =~ m|/images/(\S+)\s+((\d{1,3}\.){3}\d{1,3})|) {
        if (defined $clients->{$1} && $clients->{$1}->{'backup_ip'} eq $2) {
            $clients->{$1}->{'found'} = 1;
            $out .= $line;
        } else {
            $needs_update = 1;
        }
    }
}
close $fh;

foreach my $client (keys %$clients){
    if (!$clients->{$client}->{'found'} ) {
        $needs_update = 1;
        $out .= "/images/$client $clients->{$client}->{'backup_ip'}(rw,sync,no_root_squash)\n";
    }
}

if ($needs_update){
    open (my $fh, '>', '/etc/exports');
    print $out;
    print $fh $out;
    system("exportfs -ra") == 0 or die "Failed to export all: $!\n";
}
