#!/usr/bin/python

import sys, os
import time
import re

badlist = [
    "googlesyndication.com",
    "doubleclick.net",
    "atdmt.com",
    ]
if __name__ == "__main__":
    open_after = None
    if "--open" in sys.argv:
        open_after = True
    logfile = os.path.join(os.path.dirname(sys.argv[0]), "pagelog")
    pagelist = []
    for line in file(logfile):
        verb, url = line.rstrip().split(" ",1)
        # personal google-mail abuse
        if url.startswith("http://mail.google.com"):
            url = "http://mail.google.com/mail/"
        # other abuse:
        if filter(None, [re.search(reg, url) for reg in badlist]):
            print "FILTERING:", url
            break
        if verb == "unload":
            if url in pagelist:
                pagelist.remove(url)
        elif verb in ["load", "grease_load", "FAKE"]:
            if url not in pagelist:
                pagelist.append(url)
    for page in pagelist:
        print page
        if open_after:
            st = os.spawnvp(os.P_WAIT, "firefox", ["firefox", "-remote", 
                                                   "openurl(%s,new-tab)" % page])
            if st:
                print "non-zero status!", st
                if st == 2:
                    print "trying hard-start"
                    st = os.spawnvp(os.P_NOWAIT, "firefox", ["firefox", page])
                    # add real synchronization later
                    time.sleep(15)