#!/usr/bin/python

LOGDIR = "/home/dyuri/icesus/log"
LOG_PREFIX = "color_"
LOG_POSTFIX = "_icesus.log"

LINEPERPAGE = 300

import cgi
import os.path
import re

# regular expressions
p_prompt = re.compile(r'^Repa(.*)\xFF.')
p_password = re.compile(r'jelszo')

# colors
p_bright_colors = re.compile(r'(?P<esc>\x1B\[)1m\x1B\[3(?P<color>\d{1,2})m')
p_color = re.compile(r'\x1B\[3(?P<color>\d{1,2})m(?P<string>.*?)(?P<clear>\x1B)')
p_color_bright = re.compile(r'\x1B\[1;3(?P<color>\d{1,2})m(?P<string>.*?)(?P<clear>\x1B)')
p_rm_dstrong = re.compile(r'(?P<strong>\x1B\[1m)(?P<double>\x1B\[1m)+')
p_strong = re.compile(r'\x1B\[1m(?P<string>.*?)(?P<clear>\x1B)')
p_clear_mod = re.compile(r'\x1B\[2;37;0m')
p_sent_lines = re.compile(r'^&lt;&nbsp;(?P<string>.*?)$')

def filter(line):
    # remove prompt
    line = p_prompt.sub('', line)
    line = p_password.sub('', line)
    # standard html conversion
    line = line.replace("&", "&amp;").replace(" ","&nbsp;").replace("<","&lt;").replace(">", "&gt;").strip()
    # colors
    line = p_bright_colors.sub(r'\g<esc>1;3\g<color>m', line)
    line = p_color.sub(r'<span class="color\g<color>">\g<string></span>\g<clear>', line)
    line = p_color_bright.sub(r'<span class="bcolor\g<color>">\g<string></span>\g<clear>', line)
    line = p_rm_dstrong.sub(r'\g<strong>', line)
    line = p_strong.sub(r'<span class="bold">\g<string></span>\g<clear>', line)
    line = p_sent_lines.sub(r'<span class="sent">< \g<string></span>', line)
    line = p_clear_mod.sub('', line)
    return line

def main():
    print "Content-type: text/html\n"
    print """
<html>
<head>
  <title>Icesus logviewer</title>
  <link rel="stylesheet" href="ice.css" />
</head>
<body>
"""

    form = cgi.FieldStorage()
    if not form.has_key("logfile"):
        print "<h1>Logfile not defined!</h1>"
        return    

    if form.has_key("from"):
        lfrom = int(form["from"].value)
    else:
        lfrom = 0

    if form.has_key("to"):
        lto = int(form["to"].value)
    else:
        lto = lfrom + LINEPERPAGE

    logfile = LOG_PREFIX + form["logfile"].value + LOG_POSTFIX
    print "<div id=\"logname\">%s line %s - %s</div>" % (logfile, lfrom, lto)
    print "<pre>"
    f = open(os.path.join(LOGDIR, logfile), "r")
    l = 0
    while l < lfrom:
        l += 1
        f.readline()

    while l < lto:
        line = f.readline()
        if not line:
            break
        print filter(line)
        l += 1

    f.close()
    print """
</pre>
</body>
</html>
"""

main()

