#!/usr/bin/perl
use warnings;
use strict;
use Data::Dumper;
use lib "/opt/eig_linux/lib";
use DR::BackupServer;
use BackupServer;

my $command = shift;
my $target = shift;

my @valid_commands = qw( help usage update setup status mount unmount umount );
usage("Bad command") unless (defined $command && grep (/^$command$/, @valid_commands));
usage("Invalid userbox") unless (defined $target && $target =~ m/([a-z0-9\.\-]+|all)$/);

my %dispatch = (
    'help'      => \&usage,
    'usage'     => \&usage,
    'setup'     => \&setup,
    'status'    => \&status,
    'mount'     => \&mount,
    'umount'    => \&unmount,
    'unmount'   => \&unmount,
);

my $bk = new BackupServer;
my $partitions = $bk->get_partitions();
my @backup_clients;
foreach my $id (keys %$partitions){
    push @backup_clients, $partitions->{$id}->{'chostname'} unless grep (m/^$partitions->{$id}->{'chostname'}$/, @backup_clients);
}


if ($target =~ m/all$/) {
    foreach my $client (@backup_clients){
        $dispatch{$command}($client);
    }
} elsif (grep(m/^$target$/, @backup_clients)) {
    $dispatch{$command}($target);
} else {
    die "Unable to find $target as a backup client\n";
}

sub mount {
    my $userbox = shift;
    my $drbs = new DR::BackupServer($userbox);
    $drbs->mount();
}
sub unmount {
    my $userbox = shift;
    my $drbs = new DR::BackupServer($userbox);
    $drbs->unmount();
}
sub setup {
    my $userbox = shift;
    my $drbs = new DR::BackupServer($userbox);
    $drbs->setup();
}
sub update {
    my $userbox = shift;
    my $drbs = new DR::BackupServer($userbox);
    $drbs->update_status();
}
sub status {
    my $userbox = shift;
    my $drbs = new DR::BackupServer($userbox);
    $drbs->status();
}
sub usage {
    my $msg = shift // "";
    my $help  = qq(
Usage:
    dr_server_cli ACTION TARGET
    Available Actions: @valid_commands
    The target is typically the userbox hostname, but can also be 'all'
    );
    print "$help" . "\n$msg\n";
    exit;
}
