import os
from utils import run_bash_script_on_remote_host
from variables import PATH_TO_YARA_MALWARE_DIR,PATH_TO_YARA_RULES
# HERE Common classes to every VM agents
from agents_elements.vmagents.log import Log
from agents_elements.vmagents.ossec_conf import Ossec_conf

class Yara(Log, Ossec_conf):
    """
    Yara Vmagent class that inherits from Agents.
    Used to enhance malware detection.
    - Common to every vmagents
    - Doc: Detecting malware using YARA integration
      [https://documentation.wazuh.com/current/proof-of-concept-guide/detect-malware-yara-integration.html#detecting-malware-using-yara-integration]
    """

    def __init__(self, **kwargs):
        """
        Initialize the Yara class.

        Args:
            **kwargs: Additional keyword arguments to pass to the superclass.
        """
        super().__init__(**kwargs)
        self.path_to_yara_rules = PATH_TO_YARA_RULES

    def check_and_install_yara(self,conf_path = None):
        """
        Install YARA on the endpoint and configure it for malware detection.

        This method installs YARA on the remote host, configures the Wazuh agent to monitor
        the specified directory for file integrity, and restarts the Wazuh agent to apply
        the configuration changes.
        """

        # HERE ENDPOINT CONFIGURATION 
        monitored_path = PATH_TO_YARA_MALWARE_DIR

        # Install YARA on the remote host
        bash_script_name = 'yara_setup.sh'
        self.run_bash_script_on_remote_host(bash_script_name)

        # Define directory tags for FIM configuration
        directory_tag = {'text': monitored_path, 'realtime': 'yes', 'check_all' : 'yes', 'who-data' : 'yes'}

        # Add FIM configuration to the Wazuh agent's ossec.conf file
        
        self.add_fim_configuration(monitored_paths=[directory_tag], do_synchronize_with_VM=True, conf_path=conf_path)

        # HERE MANAGER CONFIGURATION 

    def add_yara_signature(self,new_rule):
        """
        Adds a new YARA signature to the bottom of the YARA rules file.

        Parameters:
        rules_path (str): The path to the YARA rules file.
        new_rule (str): The new YARA rule to be added.

        Returns:
        None
        """
        rules_path = self.path_to_yara_rules
        try:
            # Open the YARA rules file in append mode
            with open(rules_path, 'a') as file:
                # Write the new YARA rule to the file
                file.write("\n" + new_rule + "\n")
            print(f"Successfully added the new YARA rule to {rules_path}")
        except Exception as e:
            print(f"An error occurred while adding the YARA rule: {e}")

        

       