#!/usr/bin/env python3

import json
import re

with open('userscript.meta.js.tmpl') as f:
    meta_src = f.read()

with open('userscript.js.tmpl') as f:
    src = f.read()

# Version
with open('src/manifest.json') as f:
    version = json.loads(f.read())['version']
meta_src = meta_src.replace('%%VERSION%%', version)

# JavaScript
lines = []
with open('src/bylines.js') as f:
    for line in f.readlines():
        lines.append('\t' + line)
src = src.replace('%%JS%%', ''.join(lines))

# CSS
lines = []
with open('src/style.css') as f:
    block = ''
    for line in f.readlines():
        block += line.strip()
        
        if re.match('}\s*\n', line):
            lines.append("GM_addStyle('" + block + "');\n\t\t")
            block = ''
            continue
    lines.append("GM_addStyle('" + block + "');\n\t\t")
src = src.replace('%%CSS%%', ''.join(lines))

# Write to disk
with open('userscript.meta.js', 'w') as f:
    f.write(meta_src)
with open('userscript.js', 'w') as f:
    f.write(meta_src + "\n\n" + src)
