import sys
# HACK
sys.path.append('/home/koraty/Documenti/master_thesis/vagrant/src/prototype_configuration')

import os
import pandas as pd
import xml.etree.ElementTree as ET
from utils_wazuh import *
from variables_test import PATH_TO_OSSEC_BASE

PATH_TO_MODIFIED_OSSEC = "prototype_configuration/wazuh_library/conf_files/ossec_config_modified.conf"

# Go to the right directory:
os.chdir('vagrant/src')

# TEST: FROM CONF #
# Load existing configuration
dict_dfs = dataframe_from_conf(PATH_TO_OSSEC_BASE)
save_dataframes(dict_dfs, PATH_TO_OSSEC_BASE.replace('.conf', '.xlsx'))

# TEST: MODIFY DF #
# Ensure keys exist in dict_dfs before modifying
if 'command' not in dict_dfs:
    dict_dfs['command'] = pd.DataFrame(columns=['name', 'executable', 'timeout_allowed'])  # Define appropriate structure
dict_dfs['command'] = add_command(dict_dfs['command'], name='firewall-drop', executable='firewall-drop', timeout_allowed='yes')

if 'localfile' not in dict_dfs:
    dict_dfs['localfile'] = pd.DataFrame(columns=['log_format', 'command', 'frequency', 'location', 'alias'])  # Define appropriate structure
dict_dfs['localfile'] = add_local_file(dict_dfs['localfile'], log_format='syslog', command='syslog', frequency='360', location='/var/log/syslog', alias='syslog')

if 'active-response' not in dict_dfs:
    dict_dfs['active-response'] = pd.DataFrame(columns=['command', 'location', 'rules_id', 'timeout'])  # Define appropriate structure
dict_dfs['active-response'] = add_active_response(dict_dfs['active-response'], command='firewall-drop', location='local', rules_id='5763,5886,5447', timeout='180')

# Generate the updated ossec.conf
ossec_conf = generate_ossec_conf(dict_dfs)

# TEST: TO XLSX #
# Save the dataframes to an Excel file
save_dataframes(dict_dfs, PATH_TO_MODIFIED_OSSEC.replace('.conf', '.xlsx'))

# TEST: FROM XLSX #
# Load the dataframes from the Excel file
dict_dfs = load_dataframes(PATH_TO_MODIFIED_OSSEC.replace('.conf', '.xlsx'))

# # Generate the new XML
ossec_conf = generate_ossec_conf(dict_dfs)

# # Save the new configuration
save_dataframes(dict_dfs, PATH_TO_MODIFIED_OSSEC.replace('.conf', '.xlsx'))
save_ossec_conf(ossec_conf, PATH_TO_MODIFIED_OSSEC)

# TEST: VERIFY NEW CONF FILE #
verify_conf_file_via_bash(
    'wazidx1',
    PATH_TO_MODIFIED_OSSEC,
    do_synchronize_with_VM=True,
    is_agent=False,
    VM_conf_path=variables_test.PATH_TO_OSSEC_AGENT_MANAGER
)
