# -*- coding: iso-8859-15 -*-


# Glasnost
# By: Odile Bénassy <obenassy@entrouvert.com>
#     Romain Chantereau <rchantereau@entrouvert.com>
#     Nicolas Clapiès <nclapies@easter-eggs.org>
#     Pierre-Antoine Dejace <padejace@entrouvert.be>
#     Thierry Dulieu <tdulieu@easter-eggs.com>
#     Florent Monnier <monnier@codelutin.com>
#     Cédric Musso <cmusso@easter-eggs.org>
#     Frédéric Péters <fpeters@entrouvert.be>
#     Benjamin Poussin <poussin@codelutin.com>
#     Emmanuel Raviart <eraviart@entrouvert.com>
#     Sébastien Régnier <regnier@codelutin.com>
#     Emmanuel Saracco <esaracco@easter-eggs.com>
#
# Copyright (C) 2000, 2001 Easter-eggs & Emmanuel Raviart
# Copyright (C) 2002 Odile Bénassy, Code Lutin, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Frédéric Péters, Benjamin Poussin, Emmanuel Raviart,
#     Emmanuel Saracco & Théridion
# Copyright (C) 2003 Odile Bénassy, Romain Chantereau, Nicolas Clapiès,
#     Code Lutin, Pierre-Antoine Dejace, Thierry Dulieu, Easter-eggs,
#     Entr'ouvert, Florent Monnier, Cédric Musso, Ouvaton, Frédéric Péters,
#     Benjamin Poussin, Rodolphe Quiédeville, Emmanuel Raviart, Sébastien
#     Régnier, Emmanuel Saracco, Théridion & Vecam
#
# This program 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.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.


__doc__ = """Glasnost Applications"""

__version__ = '$Revision$'[11:-2]


import os
import sys

import glasnost.common.context as context
import glasnost.common.tools_new as commonTools


class Application:
    applicationName = None
    applicationRole = 'Undefined Role!'

    def handleGetopt(self):
        return None

    def launch(self):
        assert self.applicationName
        assert self.applicationRole != 'Undefined Role!'
        
        self.initContextOriginalOptions()

        self.initContextConfigOptions()
        self.loadConfigOptions()

        self.initContextRcOptions()
        self.loadRcOptions()

        self.initContextCommandLineOptions()
        exitCode = self.handleGetopt()
        if exitCode is not None:
            sys.exit(exitCode)
        
    def initContextCommandLineOptions(self):
        if context.get(_level = 'commandLine') is None:
            context.push(_level = 'commandLine')

    def initContextConfigOptions(self):
        if context.get(_level = 'config') is None:
            context.push(_level = 'config')

    def initContextOriginalOptions(self):
        originalContext = context.get(_level = 'original')
        if originalContext is None:
            originalContext = context.push(_level = 'original')

        originalContext.setVar('application', self)
        originalContext.setVar('verbose', 0)

    def initContextRcOptions(self):
        if context.get(_level = 'rc') is None:
            context.push(_level = 'rc')

    def loadConfigOptions(self):
        configContext = context.get(_level = 'config')

        debug = commonTools.getConfig('Misc', 'Debug') == 'true'
        configContext.setVar('debug', debug)

        dispatcherHostName = commonTools.getConfig(
                'Dispatcher', 'ServerHostName')
        if not dispatcherHostName:
            dispatcherHostName = 'localhost'
        configContext.setVar('dispatcherHostName', dispatcherHostName)

        dispatcherPort = eval(commonTools.getConfig(
                'Dispatcher', 'ServerPort'), {})
        if not dispatcherPort:
            dispatcherPort = 8000
        configContext.setVar('dispatcherPort', dispatcherPort)

        dispatcherId = 'glasnost://%s' % dispatcherHostName
        # Ensure that dispatcherId is valid.
        dispatcherId = commonTools.extractDispatcherId(dispatcherId)
        configContext.setVar('dispatcherId', dispatcherId)

        applicationId = commonTools.makeApplicationId(
                dispatcherId, self.applicationRole)
        configContext.setVar('applicationId', applicationId)

        localeDirectoryPath = commonTools.getConfig(
                'Misc', 'LocaleDir', '/usr/share/locale')
        configContext.setVar('localeDirectoryPath', localeDirectoryPath)

        logsDirectoryPath = commonTools.getConfig(
                'Misc', 'LogFilesDir', default = '/var/log/glasnost')
        configContext.setVar('logsDirectoryPath', logsDirectoryPath)

        smtpServerHostName = commonTools.getConfig(
                'Mail', 'ServerHostName')
        if not smtpServerHostName:
            smtpServerHostName = 'localhost'
        configContext.setVar('smtpServerHostName', smtpServerHostName)
        smtpServerPort = eval(commonTools.getConfig(
                'Mail', 'ServerPort'), {})
        configContext.setVar('smtpServerPort', smtpServerPort)

    def loadRcOptions(self):
        pass

    def setLogFile(self):
        logFilePath = os.path.join(
                context.getVar('logsDirectoryPath'),
                '%s.log' % self.applicationName)
        try:
            logFile = open(logFilePath, 'a', 1)
            os.chmod(logFilePath, 0640)
        except IOError:
            print 'Unable to open log file: %s' % logFilePath
            logFile = open('/dev/null', 'w')
        sys.stdout = sys.__stdout__ = logFile
        sys.stderr = sys.__stderr__ = logFile

