#!/usr/bin/env python
"""The RAS daemon (Reliability, Availability, Serviceability)"""

import logging
import sys

# Local imports are deferred until a version check is done, as they
# all need python 2.5 and die ugly without it.

def main():
    """Primary entry point for the RAS suite.  Parse command line
       options, set up logging, and invokes Engines and Analyzers."""

    # No CRLF on output message so it integrates into /etc/init.d helper
    if sys.hexversion < 0x02050100:
        sys.stdout.write("(needs Python >= 2.5.1)")
        return 42			# Magic sentinel
    from RASconfig import Globals

    Globals()      # Parse command lineAlso sets up logging

    # Each package __init__.py take care of subpackage setup order.
    import RASutils
    import Engines
    import Analyzers

    if not RASutils.Setup():   # MUST be first.  It has a duplicate check.
        return 43
    if not Engines.Setup():    # MUST be second
        return 44
    if not Analyzers.Setup():
        return 45

    # Delayed until now so early setup failures always hit stderr.
    from RASutils import daemonize
    if not Globals.opts.fg:
        if not daemonize.daemonize():
            return 46
    if not daemonize.PIDfile_create(Globals.opts.fg):
        return 47               # DON'T fall through to PIDFILE_destroy

    logging.info("HP modules currently loaded:")
    for modname in sorted(
    	[k for k, v in sys.modules.iteritems() if hasattr(v, "HP")]
    ):
        logging.info(modname)

    RASutils.EventManager.MainLoop(True)	# Supposed to run forever
    logging.warning("Exiting %s ", '-' * 40)
    daemonize.PIDfile_destroy()
    return 48

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