#!/usr/bin/python
# vim:expandtab:autoindent:tabstop=4:shiftwidth=4:filetype=python:

  #############################################################################
  #
  # Copyright (c) 2005 Dell Computer Corporation
  # Dual Licenced under GNU GPL and OSL
  #
  #############################################################################
"""bootstrap_firmware: 

usage:
    -h | --help         print this message
    -c | --config       Location of an additional config file to import
    -b | --bootstrap    run inventory in bootstrap mode
"""

from __future__ import generators

# import arranged alphabetically
import getopt
import os
import sys
import ConfigParser

# our modules
import clifuncs

class CmdlineError(Exception):pass

def runBootstrapInventory(ini, commaSeparated):
    plugins = clifuncs.getBootstrapConfig(ini, "bootstrap_")

    for pymod in plugins.get("bootstrap_inventory_plugin", []):
        try:
            module = __import__(pymod, globals(),  locals(), [])
            for package in module.BootstrapGenerator():
                if commaSeparated:
                    sys.stdout.write( "%s," % package )
                else:
                    print "%s" % package

        except (ImportError):
            pass
        except:   # don't let module messups propogate up
            #import traceback
            #traceback.print_exc()
            pass

def main():
    ini = ConfigParser.ConfigParser()
    altConfig = 0
    overrides = []
    commaSeparated=0

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:o:ub", ["help", "config=", "overrides=", "up2date_mode", "bootstrap"])
        for option, argument in opts:
            if option in ("-h", "--help"):
                print __doc__
                sys.exit(0)
            if option in ("-c", "--config"):
                clifuncs.getConfig(ini, [argument,])
                altConfig = 1
            if option in ("-u", "--up2date_mode"):
                commaSeparated=1
            if option in ("-o", "--override"):
                overrides.append(argument)
            if option in ("-b", "--bootstrap"):
                pass # ignore for backwards compat

        # load standard configuration
        if not altConfig:
            clifuncs.getConfig(ini, clifuncs.configLocations)

        for over in overrides:
            section, key, value = over.split(",", 2)
            if not ini.has_section(section):
                ini.add_section(section)
            ini.set(section, key, value)

        runBootstrapInventory(ini, commaSeparated)

    except CmdlineError, e:
        print
        print e
        print
        print __doc__
        sys.exit(2)

    except (getopt.GetoptError):
        # print help information and exit:
        print __doc__
        sys.exit(2)

    return 0 #shell logic


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

