# vim: set nosmartindent et ts=4 sw=4 :

import os, sys, re
from glob import glob
from zipfile import ZipFile, ZIP_STORED, ZIP_DEFLATED

resources = [
    "install.rdf",
    "chrome.manifest",
    "*.xul",
    "locale/*/*.dtd",
    "locale/*/*.properties",
    "defaults/preferences/prefs.js",
    "icon.png", "icon64.png",
    "LICENSE"
    ]
destination = "extension.xpi"

def get_js_requires(scripts):
    known = set()
    scripts = list(scripts)
    for script in scripts:
        with open(script) as sp:
            for line in sp:
                m = re.search(r"(?:r|lazyR)equire\((['\"])(.+?)\1", line)
                if not m:
                    continue
                m = m.group(2) + ".js"
                if m in known:
                    continue
                known.add(m)
                scripts += m,
    return set(scripts)

def get_files(resources):
    for r in get_js_requires(("bootstrap.js", "loader.jsm")):
        yield r
    for r in resources:
        if os.path.isfile(r):
            yield r
        else:
            for g in glob(r):
                yield g

if os.path.exists(destination):
    print >>sys.stderr, destination, "is in the way"
    sys.exit(1)

class ZipOutFile(ZipFile):
    def __init__(self, zfile):
        ZipFile.__init__(self, zfile, "w", ZIP_STORED)
    def __enter__(self):
        return self
    def __exit__(self, type, value, traceback):
        self.close()

with ZipOutFile(destination) as zp:
    for f in sorted(get_files(resources), key=str.lower):
        zp.write(f)

@@ -130,16 +130,312 @@
 FLATED%0A%0A
+try:%0A    from xpisign.context import ZipFileMinorCompression as Minor%0Aexcept ImportError:%0A    from warnings import warn%0A    warn(%22No optimal compression available; install xpisign%22)%0A    class Minor(object):%0A        def __enter__():%0A            pass%0A        def __exit__(*args):%0A            pass%0A%0A
 resource
@@ -1717,16 +1717,34 @@
 lose()%0A%0A
+with Minor():%0A    
 with Zip
@@ -1771,16 +1771,20 @@
  as zp:%0A
+    
     for 
@@ -1829,24 +1829,28 @@
 str.lower):%0A
+    
         zp.w

use minor compression if xpisign is installed