bin/pvl.dhcp-conf
author Tero Marttila <terom@paivola.fi>
Mon, 09 Mar 2015 23:31:13 +0200
changeset 738 3104fdf7ea26
parent 667 2d5750797b8a
permissions -rwxr-xr-x
pvl.hosts.hosts: drop support for instanced ip.* in favor of improved interface:ip.* =
#!/usr/bin/env python

"""
    Process dhcpd configs.

    Takes a conf file as input, and gives a conf file as output.
"""

import logging; log = logging.getLogger('pvl.dhcp-conf')
import optparse
import os.path
import pvl.args
import pvl.dhcp.config

def process_dhcp_items (block, items,
        include_path    = None,
):
    """
        Yield items for output from given input items.

            include_path        - rewrite includes to be relative to given path.
    """

    for item in items:
        name, args = item[0], item[1:]

        log.debug("%s: %s: %s", block, name, args)

        if name == 'include':
            include, = args
            
            if include_path:
                include = os.path.join(include_path, include)

                log.info("%s: include: %s", block, include)

            yield 'include', include

        else:
            yield item

def process_dhcp_block (block, **opts):
    """
        Return Block for output from given input Block.
    """

    log.debug("%s <- %s %s", block, block.items, block.blocks)

    block = pvl.dhcp.config.Block(block.key,
        items   = list(process_dhcp_items(block, block.items, **opts)),
        blocks  = [process_dhcp_block(subblock, **opts) for subblock in block.blocks]
    )

    log.debug("%s -> %s %s", block, block.items, block.blocks)
    
    return block

def main (argv):
    parser = optparse.OptionParser(__doc__)
    parser.add_option_group(pvl.args.parser(parser))

    parser.add_option('--include-path',         metavar='PATH',
            help="Adjust includes to use given path prefix")

    options, args = pvl.args.parse(parser, argv)
    
    for file in pvl.args.apply_files(args):
        try:
            conf = pvl.dhcp.config.DHCPConfigParser.load(file)
        except pvl.dhcp.config.DHCPConfigError as error:
            log.error("%s", error)
            return 3

        # process
        conf = process_dhcp_block(conf,
                include_path    = options.include_path,
        )
        
        # output
        for line in pvl.dhcp.config.build_block(conf):
            print line

    return 0

if __name__ == '__main__':
    pvl.args.main(main)