#!/usr/bin/env python
"""
Command-line tool to report changes in text configuration files
as NetLogger events.

The configuration file uses the INI format, with only a single
parameter, 'files', per section. This comma-separated list of patterns
is expanded by glob. The section name is given to the MonitoredFiles
constructor as the group name.

For example:

    [bellybutton]
    files: ./cfgmon.cnf

    [etc]
    files: /etc/*.conf

"""
__rcsid__ = "$Id: nl_cfgmon 23923 2009-09-18 22:42:26Z ksb $"
__author__ = "Dan Gunter (dkgunter (at) lbl.gov)"

import sys
#
from netlogger import nlapi
from netlogger.nllog import get_logger, OptionParser
from netlogger.analysis import filemon

## Functions

def main():
    # parse args
    usage = "%prog [options] [files..]"
    description = """Generate events to track changes to configuration files.
Note: When specifying file patterns in [files...], quote the pattern if you
want the program to notice new files appearing. For example: %prog "*.conf".
Otherwise, if you let the pattern be expanded on the command line, events
will only be generated for removal or re-instatement of the list of
files present at the time you run the program.
"""

    parser = OptionParser(usage=usage, description=description)
    parser.add_option('-c', '--config', metavar="FILE", action='store',
                      dest='config_file', default=None,
                      help="configuration file with desired filenames "
                      "(default=<use files on command line>)")
    parser.add_option('-o', '--output', metavar="FILE or URL",
                      action='store', dest='output_url', default=None,
                      help="output filename or NetLogger URL, such as "
                      "x-netlog://host:port or x-netlog-udp://host:port, "
                      "(default=stdout)")
    options, args = parser.parse_args()
    log = get_logger(__file__) # Should be first done, just after parsing args
    if not args and not options.config_file:
        parser.error("at least one file must be specified, either "
                     "with a configuration file or on the command line")
    if options.output_url is None:
        logfile = sys.stdout
    else:
        logfile = options.output_url
    w = nlapi.Log(logfile, guid=False)
    w.setMeta(host=nlapi.get_host())
    # init manager, which handles all other details
    log.info("init.start")
    manager = filemon.MonitoredFilesManager(config_file=options.config_file,
                                           args=args, writer=w)
    log.info("init.end", status=0)
    # loop until stopped in manager
    log.info("run.start")
    manager.loop()
    log.info("run.end", status=0)

if __name__ == '__main__':
    sys.exit(main())
