import random
import signal
from tornado import ioloop

from .zeromq import setup as setup_zmq, cleanup as cleanup_zmq
from .webapp import setup as setup_webapp
from .model import setup as setup_db
from .monitor.packet_handler import process_mon_command
from .service.packet_handler import process_svc_command
from .service.keepalive import setup as setup_keepalive, cleanup as cleanup_keepalive


def main():
    random.seed()

    # Databases
    setup_db()

    # ZeroMQ stuffs
    setup_zmq(svc_handler=process_svc_command, mon_handler=process_mon_command)

    setup_keepalive()

    # Web application
    setup_webapp()

    try:
        signal.signal(signal.SIGTERM, lambda: ioloop.IOLoop.instance().stop())
        ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
        print(' Exitting ...')
        ioloop.IOLoop.instance().stop()

    cleanup_zmq()
    cleanup_keepalive()
