#!/usr/bin/python
#
# Automatically fix Subresource Integrity links in the HTML templates.
#
# Pass templates as command-line arguments. Expects to be run from the
# base resource directory.
#

import glob
import re
import sys
from hashlib import sha384


script_rx = re.compile(r'<(?:script|link rel="stylesheet")[^>]*(?:src|href)="(?:{{.URLPrefix}})?([^"]+)"[^>]*>')
integrity_rx = re.compile(r' +integrity="[^"]*"')


def compute_checksum(src):
    if src[0] == '/':
        src = src[1:]
    with open(src) as fd:
        return 'sha384-' + sha384(fd.read()).digest().encode('base64').strip()


def replace_checksum(m):
    src = m.group(1)
    checksum = compute_checksum(src)

    script = m.group(0)
    script = integrity_rx.sub('', script)
    script = '%s integrity="%s">' % (script[:-1], checksum)

    return script


def fix_sri(path):
    with open(path) as fd:
        data = fd.read()
    result = script_rx.sub(replace_checksum, data)
    if result != data:
        print >>sys.stderr, 'updating %s' % path
        with open(path, 'w') as fd:
            fd.write(result)


if __name__ == '__main__':
    for arg in sys.argv[1:]:
        for path in glob.glob(arg):
            try:
                fix_sri(path)
            except Exception as e:
                print >>sys.stderr, "Error fixing %s: %s" % (path, e)