#!/usr/bin/env python3

__copyright__ = "Copyright 2014-2016, http://radical.rutgers.edu"
__license__   = "MIT"


import os
import sys
import time
import setproctitle

import radical.utils as ru
import radical.pilot as rp


# ------------------------------------------------------------------------------
#
def bootstrap_3(aid):
    """
    This method continues where the bootstrap_0/1/2 left off, and will now pass
    control to the Agent class which will spawn the functional components.
    Before doing so, we will check if we happen to be agent instance zero.  If
    that is the case, some additional python level bootstrap routines kick in,
    to set the stage for component and sub-agent spawning.

    The agent interprets a config file, which will specify in an 'agents'
    section:
      - what nodes should be used for sub-agent startup
      - what bridges should be started
      - what are the endpoints for bridges which are not started
      - what components should be started
    agent.0 will create derived config files for all sub-agents.
    """

    print("bootstrap agent %s" % aid)

    agent = None

    try:
        setproctitle.setproctitle('rp.%s' % aid)

        cfg = ru.Config(path='%s.cfg' % aid)
        cfg.uid  = aid
        cfg.aid  = aid  # used by executor
        cfg.path = os.getcwd()
        cfg.base = os.getcwd()

        # start a non-primary session (the agents will own their cmgrs)
        session = rp.Session(cfg=cfg, _primary=False)

        if aid == 'agent.0': agent = rp.Agent_0(cfg, session)
        else               : agent = rp.Agent_n(cfg, session)

        agent.start()

        # wait until the agent finishes or fails.
        while True:
            time.sleep(0.1)

    except:
        print('failed %s' % aid)
        ru.print_exception_trace()

    finally:
        # in all cases, make sure we perform an orderly shutdown.  I hope python
        # does not mind doing all those things in a finally clause of
        # (essentially) main...
        print('finalize %s' % aid)

        if agent:
            agent.stop()
            print('stopped  %s' % aid)


# ------------------------------------------------------------------------------
#
if __name__ == "__main__":

    # FIXME: daemonization a'la component

    if len(sys.argv) != 2:
        raise RuntimeError('missing parameter: agent id')

    bootstrap_3(sys.argv[1])


# ------------------------------------------------------------------------------
