"""Module of Trivy Scanner commands"""

import sys
from pathlib import Path

from common.gitlab_helper import GitlabHelper

sys.path.append("./senior-ci")

from docker import DOCKERHUB_ORG_NAME

from . import exec_command, get_env_variable_required

TRIVY_ERROR = "Houve um erro ao rodar o trivy, entre em contato com o time de DevOps"
ci_project_dir = get_env_variable_required("CI_PROJECT_DIR")


def _get_trivy_config():
    trivy_config_project_id = 8020
    gitlab_helper = GitlabHelper(trivy_config_project_id)

    trivy_yaml_template = (
        gitlab_helper.gitlab_project.files.get(file_path="trivy.yaml", ref="main")
        .decode()
        .decode("utf-8")
    )

    trivy_yaml_template = trivy_yaml_template.replace("$CI_PROJECT_DIR", ci_project_dir)

    with open("trivy.yaml", "w", encoding="utf-8") as trivy_yaml:
        trivy_yaml.write(trivy_yaml_template)


def scan_vulnerabilities() -> None:
    _get_trivy_config()

    Path("trivy").mkdir(parents=True, exist_ok=True)

    exec_command(
        f"trivy fs . --offline-scan --output {ci_project_dir}/trivy/vulnerabilities_scan.json",
        error_message=TRIVY_ERROR,
    )


def scan_image(image_name, custom_args, version) -> None:
    _get_trivy_config()

    Path("trivy").mkdir(parents=True, exist_ok=True)

    image_tar_path = Path(ci_project_dir).joinpath("docker_image", f"{image_name}.tar")

    if Path(image_tar_path).exists():
        exec_command(
            f"trivy image --input {image_tar_path} {custom_args} "
            f"--offline-scan --output {ci_project_dir}/trivy/docker_image_scan_{image_tar_path.stem}.json",
            error_message=TRIVY_ERROR,
        )
    else:
        exec_command(
            (
                f"trivy image {custom_args} {DOCKERHUB_ORG_NAME}/{image_name}:{version} "
                f"--offline-scan --output {ci_project_dir}/trivy/docker_image_scan.json"
            ),
            error_message=TRIVY_ERROR,
        )
