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

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

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

my %dispatch = (
    'help'          => \&usage,
    'usage'         => \&usage,
    'setup'         => \&setup,
    'status'        => \&status,
    'mount'         => \&mount,
    'umount'        => \&unmount,
    'unmount'       => \&unmount,
    'nfsmount'      => \&nfs_mount,
    'nfsunmount'    => \&nfs_unmount,
    'postsync'      => \&post_sync,
    'failover'      => \&failover,
    'failback'      => \&failback,
);

my $bk = new BackupServer;
my $clients = $bk->get_dr_clients;

if ($target =~ m/all$/) {
    foreach my $client (keys %$clients){
        $dispatch{$command}($client);
    }
} elsif ($target =~ m/^provo|houston$/) {
    foreach my $client (keys %$clients){
        $dispatch{$command}($client) if $clients->{$client}->{'dc'} eq $target;
    }
} elsif (defined $clients->{$target}) {
    $dispatch{$command}($target);
} else {
    die "Unable to find $target as a backup client\n";
}

sub mount {
    my $userbox = shift;
    my $drclient = new DR::BackupClient($userbox);
    $drclient->mount();
}
sub unmount {
    my $userbox = shift;
    my $drclient = new DR::BackupClient($userbox);
    $drclient->unmount();
}
sub nfs_mount {
    my $userbox = shift;
    my $drclient = new DR::BackupClient($userbox);
    $drclient->nfs_mount();
}
sub nfs_unmount {
    my $userbox = shift;
    my $drclient = new DR::BackupClient($userbox);
    $drclient->nfs_unmount();
}
sub setup {
    my $userbox = shift;
    my $drclient = new DR::BackupClient($userbox);
    $drclient->setup();
}
sub update {
    my $userbox = shift;
    my $drclient = new DR::BackupClient($userbox);
    $drclient->update_status();
}
sub post_sync {
    my $userbox = shift;
    my $drclient = new DR::BackupClient($userbox);
    $drclient->post_sync();
}
sub failover {
    my $userbox = shift;
    my $drclient = new DR::BackupClient($userbox);
    $drclient->failover();
}
sub failback {
    my $userbox = shift;
    my $drclient = new DR::BackupClient($userbox);
    $drclient->failback();
}
sub status {
    my $userbox = shift;
    my $drclient = new DR::BackupClient($userbox);
    $drclient->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;
}
