#!/usr/bin/env python3
# coding=utf-8
from __future__ import print_function

import os
import os.path as path
import re
import argparse
from datetime import datetime

script_dir = path.dirname(path.realpath(__file__))

defines = {}
for k, v in os.environ.items():
    if k.upper().startswith('V_'):
        defines[k[2:]] = v

print('Custom params:', ', '.join(['='.join(x) for x in defines.items()]))

parser = argparse.ArgumentParser()
parser.add_argument('--outc', default='none', help='Output C header')
parser.add_argument('--outv', default='none', help='Output Verilog header')

args = parser.parse_args()

if args.outc == 'none' and args.outv == 'none':
    print('Warning: not emitting any files. Specify arguments')

if args.outv != 'none':
    with open(args.outv, 'w') as f:
        print('''
// auto-generated by gen_config.py. DO NOT EDIT
// Generated at {date}

`ifndef VX_USER_CONFIG
`define VX_USER_CONFIG
'''[1:].format(date=datetime.now()), file=f)

        for k, v in defines.items():
            print('`define {} {}'.format(k, v), file=f)

        print('\n`endif', file=f)

if args.outc != 'none':
    with open(args.outc, 'w') as f:
        print('''
// auto-generated by gen_config.py. DO NOT EDIT
// Generated at {date}

#ifndef VX_USER_CONFIG
#define VX_USER_CONFIG
'''[1:].format(date=datetime.now()), file=f)

        for k, v in defines.items():
            print('#define {} {}'.format(k, v), file=f)

        print('\n#endif', file=f)

translation_rules = [
    # preprocessor directives
    (re.compile(r'^\s*`include .*$'), r''),
    (re.compile(r'`ifdef'), r'#ifdef'),
    (re.compile(r'`ifndef'), r'#ifndef'),    
    (re.compile(r'`elif'), r'#elif'),
    (re.compile(r'`else'), r'#else'),
    (re.compile(r'`define'), r'#define'),    
    (re.compile(r'`endif'), r'#endif'),

    # macro expansion
    (re.compile(r"`([A-Za-z_][$_0-9A-Za-z]*)"), r'\1'),

    # literals
    (re.compile(r"\d+'d(\d+)"), r'\1'),
    (re.compile(r"\d+'b([01]+)"), r'0b\1'),
    (re.compile(r"\d+'h([\da-fA-F]+)"), r'0x\1')   
]

if args.outc != 'none':
    with open(args.outc, 'a') as f:
        print('''
// auto-generated by gen_config.py. DO NOT EDIT
// Generated at {date}

// Translated from VX_config.vh:
'''[1:].format(date=datetime.now()), file=f)
        with open(path.join(script_dir, '../rtl/VX_config.vh'), 'r') as r:
            lineno = 0
            for line in r:
                for pat, repl in translation_rules:
                    match = pat.search(line)
                    if match:                        
                        line = re.sub(pat, repl, line)
                        #print("*** match @" + str(lineno) + ": " + match.group() + " => " + line)
                f.write(line)
                lineno = lineno + 1
        print('''
'''[1:], file=f)



