#!/usr/bin/env bash

DB_NAME="pentest_results.db"

# Function to truncate strings to a specified length
truncate() {
    local str="$1"
    local max_length="$2"
    if [ ${#str} -gt $max_length ]; then
        echo "${str:0:$max_length-3}..."
    else
        printf "%-${max_length}s" "$str"
    fi
}

# Print header
printf "%-15s | %-15s | %-5s | %-8s | %-15s | %-20s | %s\n" \
    "IP Address" "Hostname" "Port" "Protocol" "Service" "Version" "Vulnerability"
printf "%s\n" "$(printf '=%.0s' {1..109})"

# Query and format the results
sqlite3 -separator "|" "$DB_NAME" "SELECT ip_address, hostname, port, protocol, service, version, vulnerability FROM nmap_scans ORDER BY ip_address, port;" | 
while IFS='|' read -r ip hostname port protocol service version vulnerability; do
    ip=$(truncate "$ip" 15)
    hostname=$(truncate "$hostname" 15)
    port=$(truncate "$port" 5)
    protocol=$(truncate "$protocol" 8)
    service=$(truncate "$service" 15)
    version=$(truncate "$version" 20)
    vulnerability=$(truncate "$vulnerability" 20)

    printf "%-15s | %-15s | %-5s | %-8s | %-15s | %-20s | %s\n" \
        "$ip" "$hostname" "$port" "$protocol" "$service" "$version" "$vulnerability"
done

echo "Query completed."
