#!/bin/bash
cd /
# Source the sourcer.sh file to get the DEBUG_LEVEL variable
source /vagrant/sourcer.sh variables.sh

# Check if the target IP is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <target_ip>"
    exit 1
fi

# Replace the following with the desired target IP address or range
target=$1

# Define the log file for the Nmap scan
LOG_FILE="$PATH_TO_LOG_DIR/nmap_scan.log"

# Clear the log file at the start
: > "$LOG_FILE"

# Function to install nmap if not already installed
function install_nmap {
    log $DEBUG_LEVEL $VERBOSE_INFO "Installing Nmap..."
    if command -v apt &> /dev/null; then
        sudo apt update && sudo apt install -y nmap
    elif command -v yum &> /dev/null; then
        sudo yum install -y nmap
    else
        log $DEBUG_LEVEL $VERBOSE_ERROR "Package manager not supported. Please install Nmap manually."
        return 1
    fi
}

# Check if nmap is installed, and install it if necessary
if ! command -v nmap &> /dev/null; then
    install_nmap
    if [ $? -ne 0 ]; then
        log $DEBUG_LEVEL $VERBOSE_ERROR "Failed to install Nmap. Exiting."
        exit 1
    fi
fi

# Define the array of scan types
scan_types=("-sS" "-sT" "-sA")

# DESCRIPTION #
# To run the script use /snort-scan.sh <IP_target>

log $DEBUG_LEVEL $VERBOSE_INFO "Starting Nmap scan process for target: $target"

# Function to run a ping command on the provided target
function run_ping {
    local target="$1"

    log $DEBUG_LEVEL $VERBOSE_INFO "Running ping on $target..."
    ping "$target" -c 5
}

# Function to run an Nmap scan with the provided scan type and output to the specified file
function run_nmap_scan {
    local target="$1"
    local scan_type="$2"

    log $DEBUG_LEVEL $VERBOSE_INFO "Running Nmap scan on $target with scan type: $scan_type..."
    sudo nmap "$scan_type" "$target" -p1-3306 -oN "$LOG_FILE"
    log $DEBUG_LEVEL $VERBOSE_INFO "Scan on $target with scan type: $scan_type completed. Results saved in $LOG_FILE"
}

# Start logging the Nmap scan process
log $DEBUG_LEVEL $VERBOSE_INFO "Nmap Scan Results for $target" > "$LOG_FILE"

# Run the ping command
run_ping "$target"

for scan_type in "${scan_types[@]}"; do
    run_nmap_scan "$target" "$scan_type"
done

log $DEBUG_LEVEL $VERBOSE_INFO "All Nmap scans on $target completed. Combined results saved in $LOG_FILE"
