import re
import os
import pickle

from larpe import sessions
from mod_python import Cookie

def is_auth_ok(req):
    """ Test if you are authenticate on the Larpe server """
    cookies = Cookie.get_cookies(req, Cookie.MarshalCookie, secret='secret007')
    sessions_dir = os.path.join("%(larpe_dir)s", "sessions")
    for name, cookie in cookies.iteritems():
        value = cookie.value.replace('"', '')
        if "larpe-" in name and value in os.listdir(sessions_dir):
            try:
                file = open(os.path.join(sessions_dir, value), "rb")
                session = pickle.load(file)
                if not session.users or not session.id:
                    return False
                return True
            except Exception, err:
                return False
    return False


def filter_page(filter, page):
    r = re.compile(r"""(<a.*?href=["']).*?(["'].*?>D.*?connexion</a>)""")
    page = r.sub(r"""\1%(logout_url)s\2""", page)
    return page

def outputfilter(filter):
    """ Apache called this function by default """
    if not re.search("^/liberty/.*", filter.req.uri) and not is_auth_ok(filter.req):
        filter.write('<meta http-equiv="refresh" content="0; url=%(login_url)s" />')
        filter.close()
        return

    if filter.req.content_type is not None:
        is_html = re.search('text/html', filter.req.content_type)
    if filter.req.content_type is None or not is_html:
        filter.pass_on()
    else:
        if not hasattr(filter.req, 'temp_doc'):
            # Create a new attribute to hold the document
            filter.req.temp_doc = []
            # If content-length ended up wrong, Gecko browsers truncated data
            if 'Content-Length' in filter.req.headers_out:
                del filter.req.headers_out['Content-Length']

        temp_doc = filter.req.temp_doc
        s = filter.read()
        # Could get '' at any point, but only get None at end
        while s:
            temp_doc.append(s)
            s = filter.read()

        # The end
        if s is None:
            page = ''.join(temp_doc)
            page = filter_page(filter, page)
            filter.write(page)
            filter.close()

