from conan import ConanFile
from conan.tools.system import package_manager
from conan.errors import ConanInvalidConfiguration
from conans import AutoToolsBuildEnvironment, RunEnvironment, tools
import os


class GitConan(ConanFile):
    name = "git"
    version = "2.40.0"

    settings = "os", "compiler", "build_type", "arch"

    requires = \
        "libcurl/7.86.0", \
        "zlib/1.2.13"

    _autotools = None

    _autotools_args = [
        "NO_TCLTK=YesPlease",
        "NO_INSTALL_HARDLINKS=YesPlease",
        "RUNTIME_PREFIX=YesPlease",
        "gitexecdir=libexec/git-core",
        "template_dir=share/git-core/templates",
        "sysconfdir=etc",
        # "V=1"
    ]

    def validate(self):
        if self.settings.os not in ["Linux"]:
            raise ConanInvalidConfiguration("This recipe supports only Linux")

    def source(self):
        self.run(
            "curl -s -L -O https://github.com/git/git/archive/refs/tags/v%s.tar.gz" % self.version)
        self.run("tar -xzf v%s.tar.gz --strip 1" % self.version)

    def _build_configure(self):
        if self._autotools:
            return self._autotools

        self._autotools = AutoToolsBuildEnvironment(self)

        args = [
            "--enable-pthreads=-pthread",
            "--with-tcltk=NO",
        ]

        # Append run environment to autotools environment to have curl-config in path
        env_build_vars = self._autotools.vars
        run_environment = RunEnvironment(self)
        env_build_vars = env_build_vars | run_environment.vars

        # Build configure
        self.run("make configure")

        self._autotools.configure(args=args, vars=env_build_vars)
        return self._autotools

    def build(self):
        env_build = self._build_configure()
        tools.replace_in_file("Makefile", "EXTLIBS += -lrt", "EXTLIBS += -lrt -ldl")
        env_build.make(args=self._autotools_args)

    def package(self):
        env_build = self._build_configure()
        env_build.install(args=self._autotools_args)

    def package_info(self):
        self.env_info.PATH.append(os.path.join(self.package_folder, "bin"))

    def deploy(self):
        self.copy("*", symlinks=True)