#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2009-2010 Santhosh Thottingal <santhosh.thottingal@gmail.com>
# http://www.smc.org.in
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation; either version 3 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 Affero 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.
import sys,os   
from silpa import Silpa
sys.path.append(os.path.dirname(__file__))
from common import wsgi_fileserver, urlrelay


__author__ = 'Santhosh Thottingal (santhosh.thottingal@gmail.com)'

#relay all static file serving to wsgi_fileserver
@urlrelay.url(r'^/(js|css|doc|images)/.*', 'GET')
def static_web(environ, start_response):
    web_root = os.path.join(os.path.dirname(__file__), "web" )
    application = wsgi_fileserver.WSGIFileServerApplication(root_path = web_root)
    return application.handler(environ, start_response)

#relay module specific file serving to wsgi_fileserver
#with root as top source folder    
@urlrelay.url(r'^/modules.*$', 'GET')
def static_module(environ, start_response):
    """
        Serve the files generated by modules.
        For eg: http://domain/silpa/modules/webfonts/font/font.ttf
    """
    application = wsgi_fileserver.WSGIFileServerApplication(root_path = os.path.dirname(__file__))
    return application.handler(environ, start_response)

#relay everything else to the silpa wsgi application
@urlrelay.url(r'(.?)$')
def silpa(environ, start_response):
    silpa= Silpa()
    return silpa.serve(environ, start_response)

    
if __name__ == '__main__':
    print("Silpa server loading ...")
    port = 8080
    if len(sys.argv)> 1:
        port = int(sys.argv[1])
        
    try:
        from wsgiref.simple_server import make_server            
        print("Listening on port : " + str(port))
        print("Silpa is ready!!!")
        make_server('', port, urlrelay.URLRelay()).serve_forever()
    except KeyboardInterrupt:
        print("Keyboard Interrrupt caught, Silpa server exiting...")



