#!/usr/bin/env python3

# SPDX-FileCopyrightText: 2024 Open Mobile Platform LLC <community@omp.ru>
# SPDX-License-Identifier: BSD-3-Clause

import argparse
import os
import sys
import subprocess
from os.path import join


CONAN_EXEC_NAME = "conan-with-aurora-profile"


def main():
    known_arguments, raw_conan_arguments = parse_arguments()

    if not conanfile_path(known_arguments.source_folder):
        print("The conanfile.py or conanfile.txt file must exist", file=sys.stderr)
        return 0

    if not os.path.exists(conanrun_path(known_arguments.output_folder)):
        modified = True
    else:
        modified = is_conanfile_file_modified(
            known_arguments.source_folder, known_arguments.output_folder
        )

    if modified:
        print("The conan install will be run")
        if not install_requirements(
            conanfile_path(known_arguments.source_folder),
            known_arguments.output_folder,
            raw_conan_arguments,
        ):
            return 1
    else:
        print("The conanfile file was not modified, so skip the conan install command")
    return 0


def conanrun_path(output_folder):
    return join(output_folder, "conanrun.sh")


def conanfile_path(source_folder):
    if os.path.exists(join(source_folder, "conanfile.py")):
        return join(source_folder, "conanfile.py")
    elif os.path.exists(join(source_folder, "conanfile.txt")):
        return join(source_folder, "conanfile.txt")
    else:
        return None


def parse_arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Copy contents of package, deduplicate libraries"
    )
    parser.add_argument(
        "--source-folder",
        help="The path to the project source code files",
        required=True,
    )
    parser.add_argument(
        "--output-folder",
        help="The path to the project build directory",
        required=True,
    )
    return parser.parse_known_args()


def is_conanfile_file_modified(source_folder, output_folder):
    conanfile_file = conanfile_path(source_folder)
    return os.path.getmtime(conanfile_file) >= os.path.getmtime(
        conanrun_path(output_folder)
    )


def install_requirements(
    conanfile_file: str, output_folder: str, raw_conan_arguments: list
):
    try:
        subprocess.run(
            [
                CONAN_EXEC_NAME,
                "install",
                conanfile_file,
                f"--output-folder={output_folder}",
                *raw_conan_arguments,
            ],
            check=True,
        )
    except subprocess.CalledProcessError as error:
        print("Error during libraries installation", file=sys.stderr)
        print(error.output, file=sys.stderr)
        return False
    return True


if __name__ == "__main__":
    sys.exit(main())
