#!/bin/bash

# maximum number of processes that are allowed to exist in parallel
MAXPARALLEL=10

sod()
{
    sed 's/  / /g'
}

function jobamount
{
    jobs | grep Running | wc -l	
}

function check_job_amount
{
    while [[ $(jobamount) -ge $MAXPARALLEL ]]
    do
	sleep 1
    done
}

smb_show()
{
    echo "Found shares for $IP, starting listing"
    FILE=$1
    IP=$2
    OFILE=$IP.data

    for nl in $(egrep "<20>|<03>" $OFILE |sod |sod |sod |sod |sod |sod |sod | cut -d" " -f1|sort|uniq);
    do
	echo "###############################################################" >> $OFILE
	echo "Share Name: $nl" >> $OFILE
	smbclient -L $nl -I $IP -N >> $OFILE 2>&1
    done
    rm $IP.ready
    cat $OFILE
}

nmb_lookup()
{
    IP=$1
    touch $IP.working
    nmblookup -A $IP &> $IP.data
    if grep "No reply" $IP.data &>/dev/null
    then
	rm $IP.data
    else
	smb_show $IP.data $IP
    fi
    rm $IP.working
}

SUBNET=$1
if [[ -z "$SUBNET" ]]
then
    echo "Error, need parameter"
    exit 1
fi

rm -f $SUBNET*

for ((i=1; i<255; ++i))
do
    nmb_lookup $SUBNET.$i &
    check_job_amount
done

echo -e "Waiting for smb_scan to finish"
wait
