#!/bin/bash

# -------------------------------------------------
# NOTE: Typical Bash Script running on host machine
# -------------------------------------------------

# -------------------------------------------------
# HERE: References Section
# -------------------------------------------------
# Add your references below:
# 1. [AlienVault : Blocking malicious actors](https://documentation.wazuh.com/current/proof-of-concept-guide/block-malicious-actor-ip-reputation.html)

# HACK For debug
cd /home/koraty/Documenti/master_thesis/vagrant/

# HERE Sourcing
source logging.sh
source variables.sh
source utils.sh

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

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

# HERE: Description
log $DEBUG_LEVEL $VERBOSE_INFO "Starting script execution: $SCRIPT_NAME"

# HERE: Define paths for logs and backups
LOG_FILE="$PATH_TO_LOG_DIR/${BASENAME}.log"
initialize_log_file "$LOG_FILE"

# -------------------------------------------------
# HERE: Beginning of script
# -------------------------------------------------

# Define the path to the CSV file and scripts
CSV_FILE=$PATH_TO_CSV_NODES_INFO

# Defining scripts for each VM for brute force attack
ATTACKER_SCRIPT_PATH=$PATH_TO_ALIENVAULT_ATTACKER
DEFENDER_SCRIPT_PATH=$PATH_TO_ALIENVAULT_DEFENDER
SERVER_SCRIPT_PATH=$PATH_TO_ALIENVAULT_MANAGER

# Extract basenames for all scripts
ATTACKER_SCRIPT_NAME=$(basename "$ATTACKER_SCRIPT_PATH")
DEFENDER_SCRIPT_NAME=$(basename "$DEFENDER_SCRIPT_PATH")
SERVER_SCRIPT_NAME=$(basename "$SERVER_SCRIPT_PATH")

# Initialize error count
ERROR_COUNT=0

# -------------------------------------------------
# HERE: Checking for existence
# -------------------------------------------------

# Check if the file exists
check_file_existence "$CSV_FILE" "$ATTACKER_SCRIPT_PATH" "$DEFENDER_SCRIPT_PATH" "$SERVER_SCRIPT_PATH"

# Print the content of the CSV file for debugging
log $DEBUG_LEVEL $VERBOSE_DEBUG "CSV file content:"
cat "$CSV_FILE"

# Loop through each node in $NODES and check its type from the CSV file
while IFS=',' read -r node type ip; do
    # Skip the header row
    if [ "$node" == "Node" ]; then
        continue
    fi

    # Trim whitespace, single quotes, and carriage returns from the type variable
    type=$(echo "$type" | sed "s/^[[:space:]]*['\"]*\([^'\"]*\)['\"]*[[:space:]]*$/\1/" | tr -d '\r')

    # Log which node is being processed
    log $DEBUG_LEVEL $VERBOSE_DEBUG "Processing node $node with type $type..."

    # Use case for different node types
    case "$type" in
        "server")
            log $DEBUG_LEVEL $VERBOSE_INFO "Node $node is a server. Running server-specific script: $SERVER_SCRIPT_NAME"
            if ! ssh root@"$node" "bash -s -- '$SERVER_SCRIPT_NAME'" < "$SERVER_SCRIPT_PATH"; then
                log $DEBUG_LEVEL $VERBOSE_ERROR "SSH connection failed for server node $node. Continuing to next node."
                ERROR_COUNT=$((ERROR_COUNT + 1))
            fi
            ;;
        "defender")
            log $DEBUG_LEVEL $VERBOSE_INFO "Node $node is a defender. Running defender-specific script: $DEFENDER_SCRIPT_NAME"
            if ! ssh root@"$node" "bash -s -- '$DEFENDER_SCRIPT_NAME'" < "$DEFENDER_SCRIPT_PATH"; then
                log $DEBUG_LEVEL $VERBOSE_ERROR "SSH connection failed for server node $node. Continuing to next node."
                ERROR_COUNT=$((ERROR_COUNT + 1))
            fi
            ;;
        "attacker")
            log $DEBUG_LEVEL $VERBOSE_INFO "Node $node is an attacker. Running attacker-specific script: $ATTACKER_SCRIPT_NAME"
            if ! ssh root@"$node" "bash -s -- '$ATTACKER_SCRIPT_NAME'" < "$ATTACKER_SCRIPT_PATH"; then
                log $DEBUG_LEVEL $VERBOSE_ERROR "SSH connection failed for attacker node $node. Continuing to next node."
                ERROR_COUNT=$((ERROR_COUNT + 1))
            fi
            ;;
        *)
            log $DEBUG_LEVEL $VERBOSE_WARNING "Unknown node type for $node. Skipping node."
            ;;
    esac
done < "$CSV_FILE"


# NOTE Check for Alienvault alerts in THREAT HUNTING FIELD on the dashboard;
rule_id="100100"
log $DEBUG_LEVEL $VERBOSE_INFO "Retrieving manager logs: $PATH_TO_ALERT_LOGS and Rule ID: $rule_id"

# Call the parse_rule_id function and increment ERROR_COUNT if it returns 1
# Run the parse_rule_id function on the remote wazidx1 agent via SSH
ssh root@$MANAGER_NAME "bash -s" << 'EOF'
cd /
source /vagrant/sourcer.sh utils.sh variables.sh
parse_rule_id "$PATH_TO_ALERT_LOGS" "$rule_id"
if [ $? -ne 0 ]; then
  ERROR_COUNT=$((ERROR_COUNT + 1))
fi
EOF

# End of Script
if [ $ERROR_COUNT -eq 0 ]; then
    log $DEBUG_LEVEL $VERBOSE_INFO "Script executed successfully: $SCRIPT_NAME"
else
    log $DEBUG_LEVEL $VERBOSE_INFO "Errors encountered during script execution: $SCRIPT_NAME. Total errors: $ERROR_COUNT"
fi
