#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-2-Clause
"""Use SDK Clang and wasm-ld for IR assembly, disassembly and merging."""
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile

sdk_bin = Path(shutil.which('emcc')).resolve().parent.parent / 'bin'
kind = Path(sys.argv[0]).name
args = sys.argv[1:]

if kind == 'llvm-link':
    index = args.index('-o')
    output = Path(args[index + 1])
    inputs = args[:index] + args[index + 2:]

    with tempfile.TemporaryDirectory(prefix='cm-sdk-ir-') as folder:
        merged = Path(folder) / 'merged.o'
        subprocess.run([str(sdk_bin / 'wasm-ld'), '-r', '--save-temps', '--lto-O0', '--lto-partitions=1', *inputs, '-o', str(merged)], check=True)
        shutil.copyfile(str(merged) + '.0.0.preopt.bc', output)
elif kind in ('llvm-as', 'llvm-dis'):
    mode = '-c' if kind == 'llvm-as' else '-S'
    subprocess.run([str(sdk_bin / 'clang'), '--target=wasm32-unknown-emscripten', mode, '-emit-llvm', '-x', 'ir', *args], check=True)
else:
    raise SystemExit('Unknown LLVM operation: ' + kind)
