#!/usr/bin/env bash

if [ "$#" -ne 1 ]; then
    echo "This script formats output from the Nuclei ssl-dns-names template for use with Nessus."
    echo "If you paste the output into a Nessus scan targets, Nessus will use this instead of DNS to resolve hosts."
    echo "The related Nuclei scan command is: nuclei -t \"$HOME/nuclei-templates/ssl/ssl-dns-names.yaml\" -nc -silent -u [IP or network address] -o [output file]"
    echo "Usage: $0 /path/to/file"
    exit 1
fi

# Create an array to track unique hostnames
seen_hostnames=()

# Read the file and process each line
while read -r line; do
    # Extract the IP address using sed
    ip=$(echo "$line" | cut -d ' ' -f 4 | cut -d ':' -f 1)
    
    # Extract the hostnames using awk
    hostnames=$(echo "$line" | cut -d ' ' -f 5 | awk -F'[][]' '{print $2}')
    
    # Split hostnames and iterate over each one
    IFS=',' read -ra ADDR <<< "$hostnames"
    for hostname in "${ADDR[@]}"; do
        # Remove leading and trailing whitespace
        hostname=$(echo "$hostname" | xargs)
        
        # Check if the first character of the hostname is not an asterisk
        if [[ "${hostname:0:1}" != "*" ]]; then
            # Check if the hostname has already been seen
            if [[ ! " ${seen_hostnames[@]} " =~ " ${hostname} " ]]; then
                # Add the hostname to the seen_hostnames array
                seen_hostnames+=("$hostname")
                
                # Output the hostname and IP in the desired format
                echo "$hostname[$ip]"
            fi
        fi
    done
done < "$1"
