#!/usr/bin/env python3
# pylint: disable=C0103,C0114
#
# DESCRIPTION: Verilator: Verilog Test example --pipe-filter script
#
# Copyright 2010 by Wilson Snyder. This program is free software; you
# can redistribute it and/or modify it under the terms of either the GNU
# Lesser General Public License Version 3 or the Perl Artistic License
# Version 2.0.
# SPDX-License-Identifier: LGPL-3.0-only OR Artistic-2.0

import re
import sys

Debug = False

if Debug:
    sys.stderr.write("t_pipe_filter.pf: Hello from t_pipe_filter.pf\n")

for cmd in sys.stdin:
    if Debug:
        sys.stderr.write("t_pipe_filter.pf: gotcmd: " + cmd)

    match = re.match(r'read "(.*)"', cmd)
    if match:
        filename = match.group(1)

        wholefile = ""
        # It's faster to slurp the whole file then scan (if needed)
        with open(filename, "r", encoding="utf8") as fh:
            wholefile = fh.read()

        if 'example_lint' in wholefile:  # else short circuit
            lineno = 1
            pos = 0
            prefixes = []
            while True:
                newpos = wholefile.find('\n', pos)
                if newpos < pos:
                    break
                line = wholefile[pos:newpos]
                if 'example_lint' in line:
                    # We don't have a way to specify this yet, so just for now
                    # sys.stderr.write($line)
                    prefixes.append("int lint_off_line_" + str(lineno) +
                                    " = 1;\n")

                lineno += 1
                pos = newpos + 1

            # sys.stderr.write("Line count: %d\n" % lineno)
            wholefile = ''.join(prefixes) + wholefile

        print("Content-Length: " + str(len(wholefile)) + "\n" + wholefile)
        sys.stdout.flush()
    else:
        sys.exit("t_pipe_filter.pf: %Error: Unknown command: " + cmd)

if Debug:
    sys.stderr.write("t_pipe_filter.pf: Fin\n")

sys.exit(0)
