#!/usr/bin/env python
from __future__ import print_function
import re, os, shutil
from filecmp import cmp
from tempfile import mkstemp
for x in range(0, int(os.environ['SCRIPT_INPUT_FILE_COUNT'])):
    in_autogenerated = False
    did_autogenerate = False
    in_template = False
    categories = []
    contents = ""
    template = ""
    
    with open(os.environ['SCRIPT_INPUT_FILE_' + str(x)]) as file:
        for line in file:
            # Look for categories
            if "LogCategory" in line:
                category = None
                name = None
                category_match = re.search(r'LogCategory(.*)\(void\)', line)
                if category_match:
                    category = category_match.group(1)
                    name = category
                    name_match = re.search('_TEMPLATE_NAME\((.*)\)', line)
                    if name_match:
                        name = name_match.group(1)
                if category is not None:
                    categories.append({'Category': category, 'Name': name})
            if in_autogenerated:
                if not did_autogenerate:
                    did_autogenerate = True
                    for category in categories:
                        contents += template.format(**category)
            # Find Template section
            if "</TEMPLATE>" in line:
                in_template = False
            if in_template:
                template += re.sub(r'\$(\S+)\$', r'{\1}', line)
            if "<TEMPLATE>" in line:
                in_template = True
            # Find Autogen section
            if "</AUTOGENERATED>" in line:
                in_autogenerated = False
            if not in_autogenerated:
                contents += line
            if "<AUTOGENERATED>" in line:
                in_autogenerated = True
    # write to temporary file
    temp_fd, temp_path = mkstemp()
    with open(temp_path, 'w') as file:
        file.write(contents)
    os.close(temp_fd)
    output = os.environ['SCRIPT_INPUT_FILE_' + str(x)]
    # if not identical, move new file in to place
    if not cmp(temp_path, output):
        shutil.move(temp_path, output)
