#!/usr/bin/python -tt
# Schedwi
# Copyright (C) 2012, 2013 Herve Quatremain
#
# This file is part of Schedwi.
#
# Schedwi 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 3 of the License, or
# (at your option) any later version.
#
# Schedwi 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, see <http://www.gnu.org/licenses/>.


"""Web interface"""

from optparse import OptionParser
import os
import os.path
import sys
import gettext
import logging
import logging.handlers
import atexit
import tempfile
import fileinput

sys.path.insert(0, '/usr/lib/python2.7/dist-packages/schedwisrv')

from paste.session import SessionMiddleware
import paste.translogger
import paste.httpserver
from muntjac.demo.util import InMemorySession
from muntjac.terminal.gwt.server.application_servlet import ApplicationServlet

import parse_config
import config
import system_utils


def unlink_cert(file_name):
    """Remove the temporary pem certificate/key at exit."""
    try:
        os.unlink(file_name)
    except:
        pass


#
# Main
#

gettext.install(config.PACKAGE)

from web.main import Main

parser = OptionParser(version="%prog " + config.PACKAGE_VERSION)
parser.add_option("-c", "--config", dest="conf_file", metavar="FILE",
    help=_("use the configuration file FILE rather than the default one"))
(options, args) = parser.parse_args()

if options.conf_file is not None and not os.path.isfile(options.conf_file):
    sys.stderr.write(_("%(file)s is not a file\n") %
                     {"file": options.conf_file})
    sys.exit(1)

parse_config.parse(options.conf_file)
system_utils.change_group(parse_config.GROUP_ID)
system_utils.change_user(parse_config.USER_ID)

# Build the certificate/key pem file for the paste.httpserver.serve() function
t_file = tempfile.NamedTemporaryFile(delete=False)
atexit.register(unlink_cert, t_file.name)
os.chmod(t_file.name, 0600)  # Should be done by tempfile - just to be sure
for line in fileinput.input([parse_config.GUI_SSLCertificateFile,
                             parse_config.GUI_SSLCertificateKeyFile]):
    t_file.write(line)
t_file.close()

lh = logging.handlers.WatchedFileHandler(parse_config.GUI_LOG_FILE)
lh.setFormatter(logging.Formatter(
        '%(asctime)s schedwigui[%(process)d]: %(levelname)s: %(message)s'))
logger = logging.getLogger()
logger.addHandler(lh)
logger.setLevel(logging.INFO)

wsgi_app = ApplicationServlet(Main, debug=False,
                              contextRoot=parse_config.GUI_CONTEXT_ROOT,
                              widgetset='org.muntiacus.MuntjacWidgetSet')
wsgi_app = SessionMiddleware(wsgi_app, session_class=InMemorySession)
wsgi_app = paste.translogger.TransLogger(wsgi_app, logger=logger)
httpd = paste.httpserver.serve(wsgi_app, parse_config.GUI_IFACE_LISTEN,
                               parse_config.GUI_PORT,
                               ssl_pem=t_file.name,
                               start_loop=False)
logging.info('Serving...')
httpd.serve_forever()
