#!/usr/libexec/isilon/isi_api_d
"""
OneFS Platform API dameon, which provides a secure
 web service (HTTPS) API for retrieval of cluster performance data and
 information.
"""
import sys
from twisted.scripts._twistd_unix import UnixApplicationRunner
from twisted.python import usage

APPLICATION_PATH = '/usr/local/share/PlatformAPI'
sys.path.insert(0, APPLICATION_PATH)
# pylint: disable=F0401
# Since the import directory is dynamic, this is difficult to handle
from application import PID_FILE, SERVER_VERSION, getApplication
# pylint: enable=F0401


class IsiAPIApplicationRunner(UnixApplicationRunner):
    """
    Normal app.ApplicationRunner expects to find and load the application
    in a filed referenced in the config 'python', 'xml', 'source', 'file'
    attributes. Normally, those options are obtained thru the use of
    a ServerOptions object and then calling ServerOptions.parseOptions()
    which looks thru sys.argv parsing away.
    
    What these classes fail to do is provide for the ability to invoke
    or pass in an already instantiated application.
    API Application runner provides for this by allowing an application
    instance to be passed in and overriding the createOrGetApplication
    method to return that object instead of instantiating it out of 
    referenced file.

    """
    def __init__(self, config,  application):
        self.application = application
        super(IsiAPIApplicationRunner, self).__init__(config)

    def createOrGetApplication(self):
        return self.application



class UnixServerOptionsMixin:

    optFlags = [['nodaemon','n',
                  "don't daemonize, don't use default umask of 0077"],]

    optParameters = []



class IsiAPIServerOptions(usage.Options, UnixServerOptionsMixin):

    optFlags = []

    optParameters = []

    def __init__(self, *a, **kw):
        self['debug'] = False
        self['profile'] = None
        self['rundir'] = '.'
        self['no_save'] = True

        self['umask'] = 022
        self['chroot'] = None
        self['uid'] = None
        self['gid'] = None
        self['euid'] = 0
        
        self['syslog'] = 1
        self['prefix'] = 'isi_api_d' #syslog facility
        
        self['pidfile'] = PID_FILE
        
        usage.Options.__init__(self, *a, **kw)

    def opt_version(self):
        """Print version information and exit.
        """
        print 'isi_api_d %s' % SERVER_VERSION
        sys.exit()

    def postOptions(self):
        usage.Options.postOptions(self)
        self['originalname'] = True
        
        if self['nodaemon'] == 1:
            print 'Logging to stdout...'
            self['syslog'] = 0
            self['logfile'] = '-'
        

if __name__ == '__main__':

    config=IsiAPIServerOptions()
    try:
        config.parseOptions()
    except usage.UsageError, e:
        print 'UsageError: %s' % (str(e))
        raise SystemExit(str(e))

    IsiAPIApplicationRunner(config, getApplication()).run()

