#!/usr/bin/env python3
# encoding: utf-8
import sys
import os
import importlib.util

# Verify args
if len(sys.argv) > 1:
    python_file = sys.argv[1]
    sys.argv[1:] = sys.argv[2:]
else:
    print("<Usage> "+sys.argv[0]+" python_file arg1 arg2 ...")
    exit()

# Load the eztracepython module
eztpy_module_name = "eztracepython"
eztrace_library_path=os.getenv("EZTRACE_LIBRARY_PATH")
if eztrace_library_path:
    libdir = eztrace_library_path.split(":")[-1]+"/libeztrace-python.so"
else:
    libdir = "@CMAKE_INSTALL_PREFIX@/@CMAKE_INSTALL_LIBDIR@/libeztrace-python.so"
eztpy_spec = importlib.util.spec_from_file_location(eztpy_module_name, libdir)
eztpy_module = importlib.util.module_from_spec(eztpy_spec)
sys.modules[eztpy_module_name] = eztpy_module


# Get filters and pass module name
source_filter_name = f"eztracepython_{python_file.split('/')[-1].split('.')[0]}"
source_module_name = "__main__"
source_filename = python_file.split("/")[-1]
eztpy_module.register_filters(source_filter_name, source_filename)

# Import tested script as a module and execute it
test_spec = importlib.util.spec_from_file_location(
    source_module_name, python_file)
test_module = importlib.util.module_from_spec(test_spec)
eztpy_module.set_tracer()
test_spec.loader.exec_module(test_module)

# Disable tracing and clean C structures
eztpy_module.unset_tracer()
eztpy_module.cleanup()
