#!/bin/bash

#!/bin/bash
# Typical Bash Script running in provisionning machine

# Get the script filename (without the path) for dynamic naming
if [[ -z "$1" ]]; then
  # If no argument is provided, use $0 to get the script name
  SCRIPT_NAME="${0##*/}"
else
  # If an argument is provided, use it as the script name
  SCRIPT_NAME="$1"
fi

BASENAME="${SCRIPT_NAME%.*}"  # Remove the file extension

# -------------------------------------------------
# HERE: Source necessary variables
# -------------------------------------------------
#HACK
#cd /home/koraty/Documenti/master_thesis/vagrant/

# This loads the DEBUG_LEVEL and other variables from sourcer.sh and variables.sh
source logging.sh
source variables.sh
source utils.sh
if [ "$WAZUH_TESTS" = false ] ; then
  log $DEBUG_LEVEL $VERBOSE_INFO "Wazuh tests not activated , skipping ..."
  exit 0
fi

# -------------------------------------------------
# HERE: Description
# -------------------------------------------------

log $DEBUG_LEVEL $VERBOSE_INFO "Starting script execution: $SCRIPT_NAME"
# Run all scenarios to tests & configure wazuh agents.

# -------------------------------------------------
# HERE: Define paths and other local constants
# -------------------------------------------------

LOG_FILE="$PATH_TO_LOG_DIR/${BASENAME}.log"
initialize_log_file "$LOG_FILE"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)  # Timestamp for uniqueness
BACKUP_FILE="$PATH_TO_BACKUP_FOLDER/${BASENAME}_$TIMESTAMP.bak"
ERROR_COUNT=0

# Get the list of directories in the current directory
cd $PATH_TO_SCENARIOS_FOLDER
directories=$(ls -d */)

# Iterate through each directory
for dir in $directories; do
    # Find the .sh file at the root of the directory
    script=$(find "$dir" -maxdepth 1 -name "*.sh")

    # Check if a script was found
    if [ -n "$script" ]; then
        log $DEBUG_LEVEL $VERBOSE_DEBUG "Running script: $script"
        bash "$script"
    else
        log $DEBUG_LEVEL $VERBOSE_DEBUG "No script found in directory: $dir"
    fi
done
