# -*- coding: utf-8 -*-
# Browse the libsdl.org/cgi/docwiki.cgi documentation mirror
# Copyright (C) 2008  Sylvain Beucler
#
# 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 Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from mod_python import apache, util
import urllib
import os

def handler(req):
    if (req.path_info == ''):
        util.redirect(req, os.path.basename(req.filename) + '/FrontPage')

    req.content_type = "text/html;charset=ISO-8859-1"
    arg = req.path_info[1:] # remove leading '/'
    #req.write(req.path_info + "<br />")

    filename = urllib.pathname2url(arg)
    filename = os.path.dirname(req.filename) + "/pages/" + filename
    #req.write(filename + "<br />")

    if (not os.path.exists(filename)):
         filename = arg.replace('_', '%') # e.g. _e9 for é
         filename = urllib.url2pathname(filename)
         filename = urllib.pathname2url(filename)
         filename = filename.replace('/', '_')
         filename = os.path.dirname(req.filename) + "/pages/" + filename
         #req.write(filename + "<br />")

    if (not os.path.exists(filename)):
         filename = arg.replace('_', '%') # e.g. _e9 for é
         filename = urllib.url2pathname(filename)
         filename = filename.decode('latin-1')
         filename = filename.encode('utf-8')
         filename = urllib.pathname2url(filename)
         filename = filename.replace('/', '_')
         filename = os.path.dirname(req.filename) + "/pages/" + filename
         #req.write(filename + "<br />")

    if (not os.path.exists(filename)):
        return apache.HTTP_NOT_FOUND

    req.write(file(filename).read())
    return apache.OK
