from mod_python import apache
import os
import re

#import larpe.hosts

app_dir = '/var/lib/larpe'

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

#        filter.write(filter.req.headers_in['Cookie'])
#        delete_cookies(filter)
        #filter.req.headers_out['Set-Cookie'] = 'dc_admin="deleted"; max-age=0; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/'
        
        temp_doc = filter.req.temp_doc
        s = filter.read()
        while s: # could get '' at any point, but only get None at end
            temp_doc.append(s)
            s = filter.read()

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

def filter_dispatch(filter, page):
#    host = get_host_from_url(filter)
#    if host is None:
#        apache.log_error('Host not found')
#        return page
    try:
#        function_name = 'filter_' + host.label.lowercase()
        function_name = 'filter_' + get_proxied_site_name(filter)
        return eval(function_name + '(filter, page)')
    except NameError:
        return page
#        return filter_default(filter, page)


def filter_default(filter, page):
#    host = get_host_from_url(filter)
#    if host is None:
#        apache.log_error('Host not found')
#        return page
#    if host.auth_url is not None or host.auth_form is None:
#        return page
    form = find_auth_form(page)
    if form is not None:
        page = page.replace(form,
                            """<form method="post" action="/liberty/%s/login">
                                 <input type="submit" value="Connexion" />
                               </form>""" % get_proxied_site_name(filter))
    return page

def find_auth_form(page):
    regexp = re.compile("""<form.*?</form>""", re.DOTALL | re.IGNORECASE)
    found_forms = regexp.findall(page)

    for found_form in found_forms:
        regexp = re.compile("""<input[^>]*?type="password"[^>]*?>""", re.DOTALL | re.IGNORECASE)
        if regexp.search(found_form) is not None:
            return found_form
    return None

def get_host_from_url(filter):
    try:
        return list(Host.select(lambda x: x.reversed_hostname == filter.req.hostname \
                                          and x.reversed_directory == get_proxied_site_name(filter)))[0]
    except:
        return None


def filter_linuxfr(filter, page):
    apache.log_error(re.match('<form method="post" action="/linuxfr/login.html" id="formulaire">.*?</form>', page))
    str_to_replace = re.compile(str('<form method="post" action="/linuxfr/login.html" id="formulaire">.*?</form>'), re.DOTALL)
    return str_to_replace.sub(str(r"""<form method="post" action="/liberty/linuxfr/login" id="formulaire">
                                <div style="text-align: center; font-size: 13px;" class="loginbox">
                                <input type="submit" value="Connexion" />
                                <br />
                                <a href="/linuxfr/user_new.html">Cr&eacute;er un compte</a>
                                </div>
                                </form>"""
                                ), page)

def filter_dotclear(filter, page):
    if filter.req.uri == '/dot/ecrire/redac_list.php':
        str_to_replace = re.compile(str('(\[[^\?]+\?id=)([^"]+)(">[^\]]*)\]'), re.DOTALL)
        return str_to_replace.sub(str(r'\1\2\3 - <a href="/liberty/dot/admin_token?id=\2">token</a> ]'), page)
    if filter.req.uri == '/dot/ecrire/redacteur.php':
        str_to_replace = re.compile(str('(<form action=")redacteur.php'))
        page = str_to_replace.sub(str(r'\1/liberty/dot/admin_new_user'), page)
        str_to_replace = re.compile(str('<p class="field"><label class="float" for="user_pwd">.*?</p>'), re.DOTALL)
        return str_to_replace.sub(r'', page)
    return page




def get_abs_path(s):
    if not s:
        return s
    if s[0] == '/':
        return s
    return os.path.join(app_dir, s)
    
def get_proxied_site_path(filter):
    proxy_domain_name = filter.req.hostname
    proxied_site_dir = get_proxied_site_name(filter)
    return get_abs_path(os.path.join('sp', proxy_domain_name, proxied_site_dir))

def get_proxied_site_name(filter):
    uri_tokens = filter.req.uri.split('/')
    if uri_tokens[1] != 'liberty':
        return uri_tokens[1]
    return uri_tokens[2]
    
def delete_cookies(filter):
    success = False
    cookies_file_name = get_abs_path(os.path.join(get_proxied_site_path(filter), 'cookies_to_delete'))
    cookies_file = open(cookies_file_name, 'r')
    for cookie in cookies_file.read().split():
        if filter.req.headers_in.has_key('Cookie'):
            cookies_header = filter.req.headers_in['Cookie']
#            filter.req.temp_doc.append(filter.req.headers_in['Cookie'])
            #filter.req.temp_doc.append(cookie[len(cookie) -1:])
            cookies_match =  re.findall(cookie[:len(cookie) -1], cookies_header)
            if len(cookies_match) > 0:
                filter.req.temp_doc.append('User-Agent')
#                filter.req.temp_doc.append('%s="deleted"; max-age=0; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/' % cookie.split('=')[0])
                filter.req.headers_out['Set-Cookie'] = '%s="deleted"; max-age=0; expires=Thu, 01-Jan-1970 00:00:00 GMT; path=/' % cookie.split('=')[0]
#                cookies_file.close()
#                cookies_file = open(cookies_file_name, 'w')
                break
#            else:
#                filter.req.temp_doc.append('dommage')
    cookies_file.close()
#    if success:
#        cookies_file = open(cookies_file_name, 'w')
#        cookies_file.close()
