#!/usr/bin/env python3

import os
import re
from subprocess import Popen, PIPE
import sys

preprocess = []
compile = []
args = iter(sys.argv[1:])
verbose = int(os.environ.get("VERBOSE", 0)) != 0

while True:
    arg = next(args, None)
    if arg is None:
        break

    if arg == "-c":
        preprocess.append("-E")
        compile.append(arg)
        continue

    if arg == "-o":
        compile.append(arg)
        o_file = next(args)
        ii_file = o_file[:-1] + "ii"
        compile.append(o_file)
        continue

    if arg.endswith(".cpp"):
        cpp_file = arg
        continue

    if arg in ("-I", "-isystem"):
        preprocess.append(arg)
        preprocess.append(next(args))
        continue

    if arg.startswith("-I") or arg.startswith("-isystem"):
        preprocess.append(arg)
        continue

    preprocess.append(arg)
    compile.append(arg)

preprocess.append(cpp_file)
compile.append(os.path.realpath(ii_file))

if verbose:
    print(*preprocess)

with open(ii_file, "w") as ii, Popen(
    preprocess, stdout=PIPE, encoding="ascii"
) as pp, Popen("clang-format", stdin=PIPE, stdout=ii, encoding="ascii") as cf:
    while True:
        line = pp.stdout.readline()
        if not line:
            break
        if not re.match(r"\s*#\s*\d+", line):
            cf.stdin.write(line)

if verbose:
    print(*compile)

os.execv(compile[0], compile)
