#!/usr/bin/env python3
# Reinventory a given node (or nodes)

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

import omdclient, os, pprint, sys

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

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

## Text for --help
text = "Reinventory a given node through the check_mk API"
usage_text = "usage: %prog [options]"

#########################################################################
### subroutines #########################################################
#########################################################################

def parseServices(json):
    """
    Print a single-line report on per-host service counts and label counts,
    based on the output of /objects/service_discovery/ .  It's kinda janky.
    """
    return "%d services, %d labels (%d changed, %d vanished)" % \
        (
            len(json['extensions']['check_table']),
            len(json['extensions']['host_labels']),
            len(json['extensions']['changed_labels']),
            len(json['extensions']['vanished_labels'])
        )

#########################################################################
### 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)
    p.add_option('--tabula_rasa', dest='tabula_rasa',
        action="store_true", default=True,
        help="tabula-rasa refresh? (default: %default)")
    opt, args = p.parse_args()
    argdict = omdclient.parserArgDict(opt)
    argdict['tabula_rasa'] = opt.tabula_rasa

    error = 0
    for host in args:
        try:
            result0 = omdclient.servicesHost(host, argdict)
            before = parseServices(omdclient.servicesHost(host, argdict))
            result = omdclient.discoverServicesHost(host, argdict)
            if result:
                after = parseServices(omdclient.servicesHost(host, argdict))
                if before == after:
                    print ("%s - inventoried, no changes reported" % host)
                else:
                    print ("%s - inventoried; new: %s, old: %s" % (host, after, before))
            else:
                print ("%s - failed to inventory (no error)" % host)
                error = 1
        except Exception as e:
            print("%s - error on inventory: %s" % (host, e))
            error = 1

    sys.exit(error)

if __name__ == "__main__":
    main()

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

"""

=head1 NAME

omd-reinventory - reinventory a given node (or nodes)

=head1 SYNOPSIS

B<omd-reinventory> HOSTNAME [HOSTNAME]

=head1 USAGE

omd-reinventory runs an inventory on a host or list of hosts.

=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

L<https://docs.checkmk.com/latest/en/rest_api.html>

=head1 AUTHOR

Tim Skirvin <tskirvin@fnal.gov>

=head1 LICENSE + COPYRIGHT

Copyright 2016-2026, 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

"""
