#!/usr/bin/python
#
# -*- coding: utf-8; -*-
#
# (c) 2013 Mandriva, http://www.mandriva.com/
#
# This file is part of Pulse 2, http://pulse2.mandriva.org
#
# Pulse 2 is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Pulse 2 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pulse 2; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.

""" XMLRPC Proxy processing incoming requests from launcher """

import os
import sys

from twisted.internet import epollreactor
epollreactor.install()

from twisted.internet import reactor, task
# Filter SA warns to prevent trivial (hex/dec notation) error printing on STDOUT
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)

from mmc.site import mmcconfdir
from pulse2.scheduler.config import SchedulerConfig

import logging
import logging.config

def app() :
    from pulse2.scheduler.proxy.control import App

    config = SchedulerConfig()
    app = App(config)
    d = task.deferLater(reactor, config.initial_wait, app.run)
    @d.addCallback
    def cb(result):
        if result :
            return 0
        else :
            return 1
    @d.addErrback
    def eb(result):
        return 1


    reactor.run()
    return d

if __name__ == "__main__" :

    config_file = os.path.join(mmcconfdir, "pulse2", "scheduler", "scheduler.ini")

    if not os.path.exists(config_file):
        print "Config file '%s' does not exist." % config_file
        sys.exit(3)

    logging.config.fileConfig(config_file)
    logger = logging.getLogger()

    logger.info("XMLRPC Proxy: Reading configuration file: %s" % config_file)
    try:
        SchedulerConfig().setup(config_file)
    except Exception, e:
        logger.error("XMLRPC Proxy: %s" % str(e))
        logger.error("XMLRPC Proxy: Please fix the configuration file")
        sys.exit(1)


    sys.exit(app())
