#!/usr/bin/env python

"""The XML-RPC Bcfg2 server."""

import sys
import logging
import Bcfg2.Options
from Bcfg2.Server.Core import CoreInitError


class BackendAction(Bcfg2.Options.ComponentAction):
    """ Action to load Bcfg2 backends """
    islist = False
    bases = ['Bcfg2.Server']


class CLI(object):
    """ bcfg2-server CLI class """
    parse_first = True
    options = [
        Bcfg2.Options.Option(
            cf=('server', 'backend'), help='Server Backend',
            default='BuiltinCore', type=lambda b: b.title() + "Core",
            action=BackendAction)]

    def __init__(self):
        parser = Bcfg2.Options.get_parser("Bcfg2 server", components=[self])
        parser.parse()
        self.logger = logging.getLogger(parser.prog)

    def run(self):
        """ Run the bcfg2 server """
        try:
            core = Bcfg2.Options.setup.backend()
            core.run()
        except CoreInitError:
            self.logger.error(sys.exc_info()[1])
            return 1
        except TypeError:
            self.logger.error("Failed to load %s server backend: %s" %
                              (Bcfg2.Options.setup.backend.__name__,
                               sys.exc_info()[1]))
            raise
        except KeyboardInterrupt:
            return 1


if __name__ == '__main__':
    sys.exit(CLI().run())
