#!/usr/bin/python3
"""
*File:* run_audits_in_buildroot
*Author:* Anthony NORA
*Date:* 14/11/2024

*Description:*
    Script to run the audits on patched source files within a koji buildroot.

*License:*
    *Copyright (C) 2020-2025 "IoT.bzh"*

    *Licensed under the Apache License, Version 2.0 (the "License");\
    you may not use this file except in compliance with the License.\
    You may obtain a copy of the License at:*

    *http://www.apache.org/licenses/LICENSE-2.0*

    *Unless required by applicable law or agreed to in writing, software\
    distributed under the License is distributed on an "AS IS" BASIS,\
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\
    implied.*
    *See the License for the specific language governing permissions and\
    limitations under the License.*
"""

import argparse
import asyncio
from auditcode.core import AuditCode
import json
import logging
import os

LOG_LEVEL = logging.DEBUG

# Handle the arguments ----------------
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--tools', type=str, help='One or several tools to use to run the audit')
arg_parser.add_argument('--excludes', type=str, help='List of files to exclude from the audit')
arg_parser.add_argument('--options', type=str, help='Options to give to the tool(s)')
arg_parser.add_argument('--directory', type=str, help='Directory to audit')
arg_parser.add_argument('--resultPath', type=str, help='Path to the file that must contains the result of the audit')
arg_parser.add_argument('--logFile', type=str, default='/tmp/audit-mock-run.log', help='Location of the logging file')
args = arg_parser.parse_args()
# -------------------------------------

# Handle cleanly the logs -------------
logger = logging.getLogger('run_audits_in_buildroot')
logger.setLevel(LOG_LEVEL)
logger_format = logging.Formatter(fmt="[%(levelname)6s] [%(name)22s] : %(message)s", datefmt='%d/%m/%Y %I:%M:%S %p')
# STDERR logger
stderr_logger = logging.StreamHandler()
stderr_logger.setLevel(LOG_LEVEL)
stderr_logger.setFormatter(logger_format)
# File logger
file_logger = logging.FileHandler(args.logFile)
file_logger.setLevel(LOG_LEVEL)
file_logger.setFormatter(logger_format)
# Add handlers
logger.addHandler(stderr_logger)
logger.addHandler(file_logger)
# -------------------------------------

async def run_audit(tools: str, excludes: str, options: str, directory: str, resultPath: str):
    audit = AuditCode()

    logger.debug("Walking through the '/builddir/' directory...")
    for root, dirs, files in os.walk("/builddir"):
        for file in files:
            file_path = os.path.join(root, file)
            logger.debug(f"File found: {file_path}")

    # Convert from json serialization
    tools_list = json.loads(tools)
    excludes_list = json.loads(excludes)
    options_list = json.loads(options)
    directory_str = json.loads(directory)

    # Give some info in the logs
    logger.info(f"[audit._analyze] Tools: {tools_list} | Directory: {directory_str} | Excludes: {excludes_list} | Options: {options_list}")

    result = await audit._analyze(
        tools=tools_list,
        directory=directory_str,
        excludes=excludes_list,
        options=options_list
    )

    os.makedirs(os.path.dirname(resultPath), exist_ok=True)
    with open(resultPath, "w") as f:
        json.dump(result, f, indent=4)

    logger.info("Audit result:")
    with open(resultPath, "r") as f:
        audit_result = f.read()
        logger.info(f"\n{audit_result}")

tools = args.tools
excludes = args.excludes
options = args.options
directory = args.directory
resultPath = args.resultPath

asyncio.run(run_audit(tools, excludes, options, directory, resultPath))
