#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC

import os
import re
import sys

templ = """/*
:name: {3}
:description: black-parrot core test
:files: {0}
:incdirs: {1}
:top_module: {2}
:tags: black-parrot
:timeout: 300
*/
"""

try:
    third_party_dir = os.environ['THIRD_PARTY_DIR']
    tests_dir = os.environ['TESTS_DIR']
    conf_dir = os.environ['CONF_DIR']
except KeyError:
    print("Export the THIRD_PARTY_DIR, TESTS_DIR and CONF_DIR variables first")
    sys.exit(1)

try:
    tests_subdir = sys.argv[1]
except IndexError:
    print("Usage: ./generator <subdir>")
    sys.exit(1)

bp_path = os.path.abspath(
    os.path.join(third_party_dir, "cores", "black-parrot"))

# BlackParrot has RTL in the main repo and in the BaseJump STL submodule
cmd = "git submodule update --init --checkout {}".format(bp_path)
os.system(cmd)
print(cmd)
cmd = "cd {}; git submodule update --init --recursive external/basejump_stl".format(
    bp_path)
os.system(cmd)
print(cmd)
cmd = "cd {}; git submodule update --init --recursive external/HardFloat".format(
    bp_path)
os.system(cmd)
print(cmd)

lists = [
    {
        'name': 'bp_fe',
        'top': 'bp_fe_top',
        'flist': 'bp_fe/syn/flist.vcs'
    }, {
        'name': 'bp_be',
        'top': 'bp_be_top',
        'flist': 'bp_be/syn/flist.vcs'
    }, {
        'name': 'bp_cce',
        'top': 'bp_cce',
        'flist': 'bp_me/syn/flist.vcs'
    }, {
        'name': 'bp_lce',
        'top': 'bp_lce',
        'flist': 'bp_me/syn/flist.vcs'
    }, {
        'name': 'bp_uce',
        'top': 'bp_uce',
        'flist': 'bp_me/syn/flist.vcs'
    }, {
        'name': 'bp_unicore',
        'top': 'bp_unicore',
        'flist': 'bp_top/syn/flist.vcs'
    }, {
        'name': 'bp_multicore',
        'top': 'bp_multicore',
        'flist': 'bp_top/syn/flist.vcs'
    }
]

dirs = {
    '$BP_COMMON_DIR': 'bp_common',
    '$BP_FE_DIR': 'bp_fe',
    '$BP_BE_DIR': 'bp_be',
    '$BP_ME_DIR': 'bp_me',
    '$BP_TOP_DIR': 'bp_top',
    '$BP_EXTERNAL_DIR': 'external',
    '$BASEJUMP_STL_DIR': 'external/basejump_stl',
    '$HARDFLOAT_DIR': 'external/HardFloat',
}


def expandPaths(p):
    for d in dirs:
        p = re.sub(re.escape(d), dirs[d], p)
    return os.path.join(bp_path, p)


test_dir = os.path.join(tests_dir, 'generated', tests_subdir)

if not os.path.isdir(test_dir):
    os.makedirs(test_dir, exist_ok=True)

for l in lists:
    sources = ''
    incdirs = ''

    with open(os.path.join(bp_path, l['flist'])) as f:
        for line in f:
            line = re.sub(r'^\+define\+.*?$', '', line)
            line = re.sub(r'//.*?$', '', line)
            line = re.sub(r'#.*?$', '', line)
            res = re.match(r'^\+incdir\+(.*?)$', line)
            if res is not None:
                incdirs += expandPaths(res.group(1)) + ' '
                continue
            if len(line.strip()) > 0:
                sources += expandPaths(line.strip()) + ' '

    test_file = os.path.join(test_dir, l['name'] + '.sv')
    with open(test_file, "w") as f:
        f.write(templ.format(sources, incdirs, l['top'], l['name']))
