#!/bin/sh

# .gnmap file as first argument
if [ $# -lt 1 ] ; then
    echo '[-] parse <gnmap-file>'
    exit 1
fi

if [ ! -f "$1" ]; then
    echo '[-] No such file.'
    exit 1
fi

if [ ! -d hosts/ ]; then
    echo "[*] creating hosts/ folder"
    mkdir hosts
fi

function num_hosts {
    echo "$(cat "$1" | grep 'Up' | wc -l)"
}

# $1 is the file,  $2 must be the port, $3 must be the service-name
function parse_for_service {
    num=$(cat "$1" | grep "$2/open"  | wc -l)
    if [ $num -le 1 ]; then
        echo "[-] No hosts with service $3"
        return
    fi
    filename="hosts/hosts.$3"
    if [ -f "$filename" ]; then
        echo "[-] File exists (for service $3), skiping...."
        return
    fi

    cat "$1" | grep "$2/open" | awk '{print $2}' | sort -u > $filename
    echo "[+] Outputing all hosts ($num) with an open $3 service to $filename"
    return $num
}

# Parsing
hosts=$(num_hosts "$1")
echo "[*] A total of $hosts Hosts to parse"


parse_for_service "$1" 80 http
parse_for_service "$1" 3389 rdp
parse_for_service "$1" 22 ssh
parse_for_service "$1" 21 ftp
parse_for_service "$1" 53 dns
parse_for_service "$1" 443 https
parse_for_service "$1" 445 smb


echo "[+] Done."