#!/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 802 2008-06-06 18:15:21Z dang $"
__author__ = "Dan Gunter (dkgunter (at) lbl.gov)"

import ConfigParser
import glob
import sys
import optparse
from netlogger import util, nlapi, nllog
from netlogger.analysis import filemon

# Logging
log = nllog.NullLogger()
def activateLogging(name="netlogger.nl_cfgmon"):
    global log
    log = nllog.getScriptLogger(name)
    filemon.activateLogging()

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 = optparse.OptionParser(usage=usage, version="0.1",
                                   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()
    activateLogging("netlogger.nl_cfgmon")
    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
    manager = filemon.MonitoredFilesManager(config_file=options.config_file, 
                                           args=args, writer=w)
    # loop until stopped in manager
    manager.loop()

if __name__ == '__main__':
    main()
