#!/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
  #
  #############################################################################
"""inventory_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 runInventory(ini):
    plugins = clifuncs.getBootstrapConfig(ini, "")

    for pymod in plugins.get("inventory_plugin", []):
        try:
            module = __import__(pymod, globals(),  locals(), [])
            for package in module.InventoryGenerator():
                print "%s = %s" % (str(package), package.version)

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


def main():
    mode = "inventory"

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

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hc:bo:u", ["help", "config=", "bootstrap", "overrides=", "up2date_mode"])
        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 ("-b", "--bootstrap"):
                mode = "bootstrap"
            if option in ("-u", "--up2date_mode"):
                commaSeparated=1
            if option in ("-o", "--override"):
                overrides.append(argument)

        # 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)

        if mode == "bootstrap":
            os.execvp("bootstrap_firmware", sys.argv)
            #runBootstrapInventory(ini, commaSeparated)
        else:
            runInventory(ini)

    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() )

