# -- perl --
# Lm Host Status module for easy-4
#
# Written by Adam Kunen <ajkunen@cs.wisc.edu>
#

package Easy::Plugin::Lm;

use strict;
use warnings;

use Easy::Item;
use Easy::Helpers;
use FileHandle;
use POSIX;
use Text::Autoformat;

use lib '/s/lm-1.2/perl5/5.6.1';
use Lm;
use Lm::Defines;
use Lm::Util;
use Lm::Service::Server;

use Data::Dumper;

my $lm;

sub get_query_flags
{
    return(
        '-lm' => \&do_lm,
    );
}

sub get_usage
{
    return(
        '-lm'            => "Lm status overview",
        '-lm <host>'     => "Lm host status details",
        '-lm -c <host>'         => "Lm host status details with configuration information",
        '-lm -exec'        => "Lm pending execution queue",
    );
}


sub do_lm
{
    my ($host, $arg) = @_;

    STDOUT->autoflush(1);
    # go make our connections
    $lm = new Lm or die "Couldn't connect to database\n";
    if(!$host)
    {
        die "Invalid input, see help for more help\n";
    }
    else
    {

        # show the logs?    
        if($host eq '-showlog')
        {
            return do_lm_showlog($arg);
        }
        # Show exec queue
        elsif($host eq "-exec")
        {
            return do_lm_exec($arg);
        }
        else
        {
            my $show_config;
            if($host eq "-c")
            {
                $show_config = 1;
                $host = $arg;
            }
            $host = Easy::Helpers::fqdn($host);
                           
            return do_lm_host($host, $show_config);
        }

    }
    $lm->finish();
}

sub do_lm_exec
{
    my ($cmdstatus) = @_;
    
    # munge into Pending or Active...
    $cmdstatus = "-pending" if !$cmdstatus;
    $cmdstatus =~ s/^\-//;  # elim preceding '-'
    $cmdstatus = "\u$cmdstatus"; # cap the first letter

    my $lmcmd = "db_get$cmdstatus" . "Commands";
        
    # get the pending commands
#    my $cmds = $lm->getCommands("ACTIVE")
    my $cmds = $lm->$lmcmd()
        or die $lm->getError();

    $cmds = Lm::Util::sortCommands($cmds) if $cmdstatus eq "Pending";

    # build our attributes
    my $attrib_order = ['Active commands'];
    my $attribs = 
        {
            'Active commands' => scalar(@$cmds)
        };
    
    # build our table
    my $headings = ['CID', 'StartAt', 'Command', 'Arguments'];
    my @list;
    foreach my $cmd (@$cmds)
    {
#        print "CID: $cmd->{commandid}\n";
        my $startat = $cmd->{start_time};
        $startat = 'IMMEDIATE' if !$startat;
        
        my $args = $cmd->{arguments};
        $args = substr $args, 0, 30;
#        $args =~ tr/ /\n/;
        
        my $row = [$cmd->{commandid}, $startat, $cmd->{command}, $args];
        push @list, $row;
    }

    # return our object
    my @ret;
    push @ret, new Easy::Item
                    title                 => "$cmdstatus Commands",
                    attributes            => $attribs,
                    attributes_order     => $attrib_order,
                    headings            => $headings,
                    list                => \@list;
    return @ret;
}

sub do_lm_host
{
    my ($host, $show_config) = @_;
    
    # get the host object, and get the last log/status
    my $h = $lm->getHost($host)
        or die "Host '$host' not found in Lm database\n";
    $h->getLastLog();
    $h->checkSensors();

    # build our easy item
    my @attrib_order = 
        (
            'Hostname',
            'Board Type',
            'Afs OS Type',
        );
    my $attribs = 
        {
            'Hostname'        =>    $h->host,
            'Board Type'    =>    $h->board,
            'Afs OS Type'    =>    $h->os,
            'Host Status'    =>    $h->status,
        };
    map {
        push @attrib_order, $_;
        $attribs->{$_} = $h->$_;
    } $h->listAttributes;

    # do the sensors
    my @headings = 
        (
            'Sensor',
            'Label',
            'Class', 
            'Mode',
            'Status',
            'Value'
        );

    my @list;
    my $sensor_configs;
    foreach my $sname (sort $h->listSensors)
    {
        my $sensor = $h->sensor($sname);
        next if $sensor->status eq "IGNORE";
        
        my $value = $sensor->value;
        $value = "0" if defined $value && !$value;
        $value = "n/a" if !defined $value;
        
        # add line to table
        push @list, [$sname, $sensor->label || "", $sensor->class, $sensor->status, $sensor->currentStatus, $value];
    }

    # Create our host status item
    my @ret;
    push @ret, new Easy::Item
                    title                 => "Host Status",
                    attributes            => $attribs,
                    attributes_order     => \@attrib_order,
                    headings            => \@headings,
                    list                => \@list;


        # Return the object
    return @ret;
}


1;
