#!/usr/bin/env python
# Prints a pretty nagios report.

#########################################################################
### Declarations ########################################################
#########################################################################

import omdclient, optparse, re, os, socket, sys
from datetime import datetime

#########################################################################
### Configuration #######################################################
#########################################################################
## Managed via central libraries and /etc/omd_client

config_file_base = '/etc/omdclient/config.yaml'

## Text for --help
text = "print a pretty host/service report to STDOUT"
usage_text = "usage: %prog [options]"

#########################################################################
### Subroutines #########################################################
#########################################################################

def printHostReport(array):
    """
    Print a 2-3 line report on a host.
    """
    (host, icons, state, text, svc_ok, svc_warn, svc_crit, svc_unknown, 
        svc_pending, state_age, comments) = array
    print "%-45s  %-4s  %.25s" % (host, state, state_age)
    print "  %s" % text.encode('utf-8')
    if comments:
        p = re.compile ('\(Nagios Process\): This .* has been scheduled for fixed downtime')
        comments = p.sub ('DOWNTIME', comments)
        print "  ACK - %-70.70s" % comments


def printSvcReport(array):
    """
    Print a 2-3 line report on a service.
    """
    (crit, host, svc, tags, text, state_age, check_age, perfometer, \
        comments) = array
    print "%-45s  %-4s  %.25s" % ("%s/%s" % (host, svc), crit, state_age)
    print "  %s" % text.encode('utf-8')
    if comments:
        print "  ACK: %-70.70s" % comments

#########################################################################
### main () #############################################################
#########################################################################

def main():
    config_file = os.environ.get('OMDCONFIG', config_file_base)
    try:
        config = omdclient.loadCfg (config_file)
    except Exception, e:
        print "failed to load config: %s" % (e)
        sys.exit(3)

    p = omdclient.generateParser(text, usage_text, config)
    opt, args = p.parse_args()
    argdict = omdclient.parserArgDict(opt)

    try:
        host_ack   = omdclient.nagiosReport('host_ack',   argdict)
        host_unack = omdclient.nagiosReport('host_unack', argdict)
        svc_ack    = omdclient.nagiosReport('svc_ack',   argdict)
        svc_unack  = omdclient.nagiosReport('svc_unack', argdict)

        string = "%35s  %3d matches"
        print string % ('Acknowledged Host Alerts',      len(host_ack))
        print string % ('Unacknowledged Host Alerts',    len(host_unack))
        print string % ('Acknowledged Service Alerts',   len(svc_ack))
        print string % ('Unacknowledged Service Alerts', len(svc_unack))

        if len(host_unack) > 0:
            print ""
            print "Unacknowledged Host Alerts"
            print "=========================="
            for i in host_unack: 
                print "" 
                printHostReport(i)

        if len(host_ack) > 0:
            print ""
            print "Acknowledged Host Alerts"
            print "========================"
            for i in host_ack: 
                print "" 
                printHostReport(i)

        if len(svc_unack) > 0:
            print ""
            print "Unacknowledged Service Alerts"
            print "============================="
            for i in svc_unack: 
                print "" 
                try:
                    printSvcReport(i)
                except Exception, e:
                    print "(  error on print, skipping)"

        if len(svc_ack) > 0:
            print ""
            print "Acknowledged Service Alerts"
            print "==========================="
            for i in svc_ack: 
                print ""
                try:
                    printSvcReport(i)
                except Exception, e:
                    print "(  error on print, skipping)"

        print ""
        print "-- "
        format = "%-15.15s  %-61.61s"
        print format % ("Generated At", \
            datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        print format % ("Generated By", ("%s:%s" \
                % (socket.gethostname(), sys.argv[0])))
        print format % ("Pulled From", \
            ("https://%s/%s/check_mk" % (opt.server, opt.site)))
            
    except Exception, e:
        print "failed to generate the report: %s" % (e)
        sys.exit(-1)
    
if __name__ == "__main__":
    main()

#########################################################################
### POD Documentation ###################################################
#########################################################################

"""

=head1 NAME

omd-nagios-report - prints a report of all open host and service alerts

=head1 SYNOPSIS

B<omd-nagios-report>

=head1 USAGE

omd-nagios-report prints a report om all acknowledged and unacknowledged
host and service alerts associated with the given server and site.  

=head1 ARGUMENTS

=over 4

=item B<--debug>

If set, print debugging information.

=item B<--apikey> I<key>

Password for the API User.  Default: comes from the configuration file.

=item B<--server> I<server>

Host name of the server.  Default: comes from the configuration file.

=item B<--site> I<site>

Site name within the server.  Default: comes from the configuration file.

=item B<--user> I<user>

API User name.  The user must exist on the server, and be an 'automation
user'.  Default: comes from the configuration file.

=back

=head1 FILES

=over 4

=item F</etc/omdclient/config.yaml>

=back

=head1 SEE ALSO

https://mathias-kettner.de/checkmk_wato_webapi.html

=head1 AUTHOR

Tim Skirvin <tskirvin@fnal.gov>

=head1 LICENSE + COPYRIGHT

Copyright 2015, Fermi National Accelerator Laboratory

This program is free software; you may redistribute it and/or modify it
under the same terms as Perl itself.

=cut

"""
