import os
import subprocess

from setuptools import setup
from setuptools.command.build_py import build_py

COMMON_VERSION = "5.0.2"
SETUP_PATH = os.path.abspath(__file__)
COMMON_EXPORTS_PATH = os.path.abspath(os.path.join(SETUP_PATH, "../../../exports"))


class CommonBuild(build_py):
    def run(self):
        if os.environ.get("EDUVPN_COMMON_BUILD_SO", "0") == "1":
            try:
                subprocess.run(
                    [
                        "go",
                        "build",
                        "-o",
                        f"eduvpn_common/lib/libeduvpn_common-{COMMON_VERSION}.so",
                        "-buildmode=c-shared",
                        COMMON_EXPORTS_PATH,
                    ],
                    env={**os.environ, "CGO_ENABLED": "1"},
                    check=True,
                    capture_output=True,
                    text=True,
                )
            except subprocess.CalledProcessError as e:
                print("eduvpn-common build failed with exit code:", e.returncode)
                print("standard output:", e.stdout)
                print("error output:", e.stderr)
                raise
        super().run()


setup(cmdclass={"build_py": CommonBuild})
