#!/usr/bin/env python3

import configparser
import sys

def print_help():
    print("Unified FPGA synthesizer frontend\r\n(c) Joppe Blondel - 2022\r\n")
    print(f"Usage: {sys.argv[0]} [ OPTIONS ] target")
    print("")
    print("Options:")
    print("  -h                 Show this help message")
    print("  -c <file>          Configuration file, defaults to project.cfg")

if __name__=="__main__":
    # Parse arguments
    i = 1
    nextarg = None
    configpath = 'project.cfg'
    target = ''
    while i<len(sys.argv):
        if nextarg is not None:
            if nextarg=='config':
                configpath = sys.argv[i]
                nextarg = None
            else:
                nextarg = None
        elif sys.argv[i]=='-h':
            print_help()
            exit(0)
        elif sys.argv[i]=='-c':
            nextarg = 'config'
        else:
            target = sys.argv[i]
        i += 1
    if nextarg is not None:
        print("ERROR: expected more arguments")
        exit(1)

    config = configparser.ConfigParser()
    config.read(configpath)

    subprocesses = []

    try:

        toolchain = config.get(f'target.{target}', 'toolchain', fallback='NONE')
        if toolchain=='NONE':
            print("ERROR: No toolchain specified for target")
            exit(1)
        
        try:
            exec(f"from remotesyn.toolchains.{toolchain} import do")
        except ImportError:
            print(f"ERROR: Unknown toolchain '{toolchain}'")
            exit(1)

        ret = do(config, target, print, subprocesses)

        if ret!=0:
            exit(ret)

    except KeyboardInterrupt:
        print("\rStopping rbuild")
        for p in subprocesses:
            p.kill()
        exit(0)