#!/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(main_args):
    """Primary entry point for the RAS suite.  main_args are treated
    as command-line options."""

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

    Globals.parse_cmdline(main_args)	# Also 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.
    if not Globals.opts.fg:
        if not daemonize.daemonize():
            return 46
    if not daemonize.PIDfile_create():	# Another duplicate check, but...
        return 47               # ...DON'T fall through to PIDFILE_destroy

    for modname in sorted(
    	[k for k, v in sys.modules.iteritems() if hasattr(v, "HP")]):
        logging.debug("HP module %s", 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(sys.argv[1:]))
