#!/usr/bin/perl
use strict;
use IO::Socket::INET;
use YAML::XS;
use lib "/opt/eig_linux/lib";
use BackupServer;

my $bk = new BackupServer();

my $opts = { enable => \&enable, disable => \&disable, status => \&status } ;
my $maintfile = '/etc/sysconfig/maint';

my $continue = 0;
foreach(keys %{$opts}){
    if($ARGV[0] eq $_){
        $continue = 1;
        last;
    }
}

help() unless $continue;

my $clients = $bk->get_clients();
my $docker = -f '/opt/eig_linux/etc/puppetfeatures/docker_backups' ? 1 : 0;
$opts->{$ARGV[0]}->($ARGV[1]);

###################  subs  ##################

# Returns the hostname and ip given either
sub host_info {
    my $query = shift;
    my ($ip,$host);
    if ($query =~ /(\d{1,3}\.){3}\d{1,3}/){ 
        $ip = $query;
        $host = ip_to_host($ip); 
    } else { 
        $host = $query; 
        $ip = $clients->{$host}->{ip} if defined $clients->{$host};
    }
    if (!$host || !defined $ip) { 
        $bk->logger('LOG_ERR', "Unable to find client info for $query");
        die;
    }
    return $host, $ip; 
}

# Returns the host for a given IP
sub ip_to_host { 
    my $ip = shift;
    for my $client (keys %$clients){
        return $client if ($clients->{$client}->{ip} eq $ip );
    }
    return "";
}

# Enables maintenance mode globally or on an individual host
sub enable {
    my $data = shift;

    if ($data) {
        my ($host,$ip) = host_info($data); 
        $bk->logger('LOG_NOTICE',"ENABLING MAINTENANCE MODE FOR $host");
        $maintfile = "$maintfile-$ip";
        unless (-e $maintfile) {
            open my $fh, '>', $maintfile or die "Cannot create $maintfile: $!";
            close $fh;
        }
        if ($docker) { 
            $bk->logger('LOG_NOTICE',"Killing docker container for $host");
            system("/opt/eig_linux/bin/docker-control --up")
        }
    } else {
        $bk->logger('LOG_NOTICE',"ENABLING GLOBAL MAINTENANCE MODE");
        unless (-e $maintfile) {
            open my $fh, '>', $maintfile or die "Cannot create $maintfile: $!";
            close $fh;
        }
    }
}

# Disables maintenance mode globally or on an individual host
sub disable {
    my $data = shift;

    if ($data) {
        my ($host,$ip) = host_info($data); 
        $bk->logger('LOG_NOTICE',"DISABLING MAINTENANCE MODE FOR $host");
        $maintfile = "$maintfile-$ip";
        unlink $maintfile;
        if ($docker) { 
            $bk->logger('LOG_NOTICE',"Starting up docker containers");
            system("/opt/eig_linux/bin/docker-control --up")
        }
    } else {
        $bk->logger('LOG_NOTICE',"DISABLING MAINTENANCE MODE");
        unlink $maintfile;
    }
}

# Prints the maintenance status
sub status {
    my $global = -e $maintfile ? "ENABLED" : "DISABLED";
    print "\nglobal maintenance is $global\n\n";

    print "clients connected:\n";
    my @ips = split("\n",qx(netstat -atpn | grep 2049 | grep 'EST'|awk '{print \$5}'|cut -d: -f1|sort|uniq));
    for my $ip ( sort @ips ) {
        my $host = ip_to_host($ip);
        my $maint = -e "$maintfile-$ip" ? "  <-- MAINTENANCE" : "";
        print "$ip ($host)$maint\n";
    }

    print "\n";
    for my $client (keys %$clients){ 
        my $ip = $clients->{$client}->{ip};
        if (-f "$maintfile-$ip") { 
            print "$ip ($client) is tagged MAINTENANCE\n";
        }
    }
}

# Prints the usage banner
sub help {
    print <<EOF;
USAGE:  maint [enable [hostname] | disable [hostname] | status]

enable  - sets backup box to global maintenance mode, triggers stop iscsi on clients
                if hostname or ip is given, sets just that client to maintenance
disable - removes maintenance status from backup box, triggers iscsi start on clients
                if hostname or ip is given, removes maintenance from that client only
status  - prints maintenance status and lists connected clients
EOF
    exit;   
}
