#!/usr/bin/env python

import sys, re, time

path = "/usr/local/etc/postfix/aliases"
f=open(path)
lines = f.read().split("\n")
f.close()
mail_alias = dict()
order = []

for line in lines:
    if line.strip()=='' or line.strip()[0] == "#":
        continue

    line = re.sub("\s", "", line.strip()).split(":")
    if len(line) >= 2:
        current = line[0]
        if re.match("^owner", current): 
            current = ":skip"
        else:
            order.append(current)
        mail_alias[current] = []
        line = line[1:]

    if current == ":skip": continue
    
    if re.match(":include:", ":".join(line)):
        filename = line[2].split(",")
        f = open(filename[0])
        line = [re.sub("\s", "" , ",".join(filename[2:]) + "," + f.read())]
    mail_alias[current].extend(filter(lambda x: x!='', ":".join(line).split("#")[0].split(",")))

other =[]
print """
<head>
    <title>CSIE Mail Aliases</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script>
        $(window).load(function(){
            $(".hide").hide();
            $(".hide, .show").click(function(){
                $(this).toggle();
                $(this).next().toggle();
            });
            $(".status").click(function(){
                $(this).toggle();
                $(this).prev().toggle();
                
            });
        });
    </script>
</head>
"""
print "<body>"
print "<div>This mail list is automatic generated by alias2html @ %s</div>" % time.strftime("%Y-%m-%d %H:%M")
print "<h1>CSIE Mail Aliases</h1>"
for alias in order:
    if len(mail_alias[alias]) == 1:
        other.append("<div><span style='font-weight:bold'>%s</span> %s</div>" % (alias, mail_alias[alias][0]))
    elif re.match("^(inm_)?[rpdfbj]\d{2,}", alias) !=None or re.match("csie\d{4}", alias)!=None:
        continue
    elif len(mail_alias[alias]) > 30:
        print "<h2>" + alias + "</h2>"
        print "<div class='hide'>" + ", ".join(mail_alias[alias]) +"</div><div class='status'>click to view</div>"

    else:
        print "<h2>" + alias + "</h2>"
        print "<div class='show'>" + ", ".join(mail_alias[alias]) + "</div><div class='status' style='display:none'>click to view</div>"

print "<h2>other</h2>"
print "<div class='hide'>"
for line in other:
    print line
print "</div><div class='status'> click to view</div>"
print "</body>"


