#!/usr/bin/env python3
"""
Created/Read/Update/Delete interface to the OMD WATO API.
"""

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

import omdclient, optparse, os, re, sys

#########################################################################
### Configuration #######################################################
#########################################################################

## Central configuration file.
config_file_base = '/etc/omdclient/config.yaml'

## Default values for role/instance/extra for create/update.
role = 'UNSET'
instance = 'UNSET'
extra = 'UNSET'
folder = 'UNSET'
ip = 'UNSET'

## Text for --help
text = "Manage a given host in OMD, using the WATO API"
usage_text = "usage: %prog [create|read|update|delete] HOSTNAME [options]"

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

def printReport(result, opt):
    """
    Given the result from query(), print a useful report regarding the
    host.
    """
    att = result['attributes']
    print(result['hostname'])
    if att.get('alias', None):
        print("  %-20s %s" % ('alias', att['alias']))
    print("  %-20s %s" % ('folder',       result['path']))
    print("  tags")
    for i in sorted(att):
        m = re.search('tag_(.*)', i)
        if m:
            tag = m.group(1)
            if tag is not None:
                if i in att:
                    print("    %-40s %s" % (tag, att.get(i)))

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

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

    p = omdclient.generateParser(text, usage_text, config)
    group = optparse.OptionGroup(p, 'create/update options')
    group.add_option('--role', dest='role', default=role,
        help='role name (default: %default)')
    group.add_option('--instance', dest='instance', default=instance,
        help='instance name (default: %default)')
    group.add_option('--extra', dest='extra', default=extra,
        help='extra flags (space separated, default: %default)')
    group.add_option('--folder', dest='folder', default=folder,
        help='set WATO folder (default: %default)')
    group.add_option('--ip', dest='ip', default=ip,
        help='set IP address')
    p.add_option_group(group)
    opt, args = p.parse_args()

    argdict = omdclient.parserArgDict(opt)
    argdict['instance'] = opt.instance
    argdict['role'] = opt.role
    argdict['extra'] = opt.extra
    if not opt.folder == 'UNSET':
        argdict['folder'] = opt.folder
    if not opt.ip == 'UNSET':
        argdict['ip'] = opt.ip

    if len(args) != 2:
        p.print_help()
        sys.exit(1)

    request = args[0]
    host = args[1]

    try:

        if request == 'create':
            value, result = omdclient.createHost(host, argdict)
            if value is False:
                if result is None: print("%s - unknown error" % host)
                else: print("error on create: %s" % result)
                sys.exit(1)

            print("%s - host created, will now inventory..." % host)

            value1, result1 = omdclient.discoverServicesHost(host, argdict)
            if value1 is False:
                if result is None: print("%s - unknown error" % host)
                else: print("error on inventory: %s" % result)
                sys.exit(1)
            else:
                print("%s - %s" % (host, result1))
                sys.exit(0)

        elif request == 'inventory':
            value1, result1 = omdclient.discoverServicesHost(host, argdict)
            if value1 is False:
                if result is None: print("%s - unknown error" % host)
                else: print("error on inventory: %s" % result)
                sys.exit(1)
            else:
                print("%s - %s" % (host, result1))
                sys.exit(0)

        elif request == 'read':
            value, result = omdclient.readHost(host, argdict)
            if value is False:
                if result is None: print("%s - unknown error" % host)
                else: print(result)
                sys.exit(1)
            else:
                printReport(result, opt)
                sys.exit(0)

        elif request == 'update':
            value, result = omdclient.updateHost(host, argdict)
            if value is False:
                if result is None: print("%s - unknown error" % host)
                else: print("error on update: %s" % result)
                sys.exit(1)

            print("%s - host updated, will now inventory..." % host)

            value1, result1 = omdclient.discoverServicesHost(host, argdict)
            if value1 is False:
                if result is None: print("%s - unknown error" % host)
                else: print("error on inventory: %s" % result)
                sys.exit(1)
            else:
                print("%s - %s" % (host, result1))
                sys.exit(0)

        elif request == 'delete':
            value, result = omdclient.deleteHost(host, argdict)
            if value is False:
                if result is None: print("%s - unknown error" % host)
                else: print(result)
                sys.exit(1)
            else:
                print("%s - host deleted" % host)
                sys.exit(0)

        else:
            p.print_help('invalid request name: %s' % request)
            sys.exit(1)

    except Exception as e:
        print("failed to %s: %s" % (request, e))
        sys.exit(-1)

if __name__ == "__main__":
    main()

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

"""

=head1 NAME

omd-host-crud - create/read/update/delete omd host entries

=head1 SYNOPSIS

B<omd-host-crud> create cms-foo --role unconfigured

B<omd-host-crud> inventory cms-foo

B<omd-host-crud> read cms-foo

B<omd-host-crud> update cms-foo --instance dev

B<omd-host-crud> delete cms-foo

=head1 USAGE

omd-host-crud provides a CRUD (Create/Read/Update/Delete) interface
to the OMD/WATO check_mk web interface.

=head1 ARGUMENTS

=head2 REQUIRED

=over 4

=item I<action>

create, inventory, read, update, delete.

=item I<hostname>

Hostname for which to query.  No default, must be set.

=back

=head2 DEFAULT

=over 4

=item B<--debug>

If set, print debugging information.

=item B<--help>

Print this information and exit.

=back

=head2 CONNECTION OPTIONS

=over 4

=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

=head2 CREATE/UPDATE OPTIONS

=over 4

=item role

check_mk role name.  This can either be simple ('bastion') or more complex
based on group name ('htcondor_cmsgrid_worker').  Must already exist on
the server side.

=item instance

check_mk instance name.  This can be 'test', 'dev', 'itb', or anything
else that seems appropriate.  Must already exist on the server side.

=item extra

Not yet in use.  If you set to 'unmonitored', then we'll delete the entry.

=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-2017, 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

"""
