#!/usr/bin/perl

use strict;
use Getopt::Long;
use YAML qw( LoadFile );

my $config_dir = "/opt/eig_linux/conf";
my $bin_dir = "/opt/eig_linux/bin";
my $config_file = "partitions.yaml";
my ($part,$host,$num,$ip);
GetOptions ("p|part=s"            => \$part),
        or die("Error in command line arguments\n");
&usage and exit if ( !$part );
die "Can't find local partition /dev/backup/$part\n" if ( !-e "/dev/backup/$part" );
$num = $1 if ( $part =~ m/^[\w\d]+\.(\d*)\D+$/ );
die "Could not determine backup number from $part\n" if ( !$num );

my $current_config = LoadFile("$config_dir/$config_file") or die "Can't load local config: $!\n";
foreach my $entry ( keys %{ $current_config } ) {
	if ( $$current_config{$entry}{plabel} eq $part ) {
		$host = $$current_config{$entry}{chostname};
		$ip = $$current_config{$entry}{backnetip};
	}
}
die "Could not determine client hostname for $part\n" if ( !$host );
die "Could not determine client IP for $part\n" if ( !$ip );

print "Unmount $host:/$part and fsck? [y|N]: ";
die unless (<STDIN> =~ m/^y/i);

print "Unexporting $part\n";
system("exportfs -u $ip:/home/$host/backup$num") == 0 or die "Failed: $!\n";
#print "Commenting out $part in /etc/exports\n";
#comment out <part> in /etc/exports

print "Unmounting $part\n";
system("umount /home/$host/backup$num") == 0 or print "Failed: $!\n";
#print "Commenting out $part in /etc/fstab\n";
#comment out <part> in /etc/fstab

print "Running fsck on $part\n";
system("fsck -y /dev/backup/$part") == 0 or print "Failed: $!\n";

#print "Uncommenting $part in /etc/fstab\n";
#uncomment out <part> in /etc/fstab
print "Mounting $part\n";
system("mount /home/$host/backup$num") == 0 or die "Failed: $!\n";

#print "Uncommenting $part in /etc/exports\n";
#uncomment out <part> in /etc/exports
print "Exporting $part\n";
system("exportfs -a") == 0 or die "Failed: $!\n";

print "Complete!\n\n";

sub usage {
	print qq{\nUsage:
\t$0 -p|--part=<partition name>

};
}
