#!/bin/bash
# Typical Bash Script running in provisioning 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


# Go to root
cd /

# -------------------------------------------------
# HERE: Source necessary variables
# -------------------------------------------------

# This loads the DEBUG_LEVEL and other variables from sourcer.sh and variables.sh
source /vagrant/sourcer.sh variables.sh

# -------------------------------------------------
# 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"

# Initialize error count
ERROR_COUNT=0

# -------------------------------------------------
# HERE: Checking requirements
# -------------------------------------------------
# Check if hydra is installed
check_and_install_package "nikto"

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


# Check if the victim is reachable
ensure_reachability $DEFENDER_IP

# Use nikto to web attack the victim website
log $DEBUG_LEVEL $VERBOSE_DEBUG "Starting web attack using nikto..."

#NOTE Avoid too heavy attack to overload logs on the agent.

# Run nikto and redirect stderr to the log file
sudo nikto -h "http://$DEFENDER_IP/dvwa" -no404 -nolookup -nointeractive -nossl 2>> "$LOG_FILE"

# Check the exit code of nikto or the log file for failure signs
if [ $? -eq 0 ]; then
    if grep -q "ERROR: Unable to connect" "$LOG_FILE"; then
        log $DEBUG_LEVEL $VERBOSE_ERROR "Web DVWA attack failed - site not reachable."
        ERROR_COUNT=$((ERROR_COUNT + 1))
    else
        log $DEBUG_LEVEL $VERBOSE_DEBUG "Web DVWA attack completed."
    fi
else
    log $DEBUG_LEVEL $VERBOSE_ERROR "Web DVWA attack failed - Nikto encountered an error."
    ERROR_COUNT=$((ERROR_COUNT + 1))
fi


#BUG IP still reachable.
ensure_unreachability $DEFENDER_IP

# -------------------------------------------------
# End of Script
# -------------------------------------------------

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