#!/bin/bash

autofs_key=$1

if [ -z "$autofs_key" ]; then

    exit
    
fi

FILESYSTEM="cifs"
CREDENTIAL_FILE=/etc/mount.smb.cred

if [ -n "$CREDENTIAL_FILE" ]; then

    if [ ! -f "$CREDENTIAL_FILE" ]; then

	unset CREDENTIAL_FILE
    
    fi
    
fi

tmpvar=$(cat /proc/filesystems | grep "^nodev.*$FILESYSTEM")

if [ -z "$tmpvar" ]; then


    echo "Filesystem $FILESYSTEM not supported on this machine."
    exit
    
fi

unset tmpvar


if [ -z "$TMPDIR" ]; then

    if [ ! -d /tmp ]; then
    
	exit
	
    else
    
	TMPDIR=/tmp/auto.network
	
    fi
    
    if [ ! -d "$TMPDIR " ]; then
    
	install --directory $TMPDIR
	
    fi
    
fi


if [ "$autofs_key" = "Windows Network" ]; then


    NMBLOOKUP=$(which nmblookup 2>>/dev/null)

    if [ -z "$NMBLOOKUP" ]; then

	echo "Cannot continue: nmblookup not found."
	exit

    fi

    SMBCLIENT=$(which smbclient 2>>/dev/null)

    if [ -z "$SMBCLIENT" ]; then

	echo "Cannot continue: smbclient not found."
	exit
    
    fi

    # lookup every host in subnet
    
    $NMBLOOKUP --debuglevel= 0 '*' | grep '<00>' > $TMPDIR/SMBhosts
    
    # start of multi mount map
    # when a credentialsfile is found use this
    
    if [ -n "$CREDENTIAL_FILE" ]; then
    
	echo -n "-fstype=$FILESYSTEM,credentials=\"$CREDENTIAL_FILE\" "
    
    else

	echo -n "-fstype=$FILESYSTEM,guest "
	
    fi


    for smbhost in $(cat $TMPDIR/SMBhosts); do
    
	# determine the resources available on this host

	if [ -n "$CREDENTIAL_FILE" ]; then
	
	    $SMBCLIENT -g -L $smbhost -A "$CREDENTIAL_FILE" 2>>/dev/null > $TMPDIR/$smbhost.sharesinfo

	else
		
	    $SMBCLIENT -g -N -L $smbhost 2>>/dev/null > $TMPDIR/$smbhost.sharesinfo
	    
	fi
	
	# find more info (netbiosname for example) of this host
	# only take the 00 records
    
	$NMBLOOKUP --debuglevel=0 -A $smbhost 2>>/dev/null | grep ' <00> ' > $TMPDIR/$smbhost.serverinfo
    
    
	if [ -f $TMPDIR/$smbhost.sharesinfo -a -f $TMPDIR/$smbhost.serverinfo ]; then
    
	    
	    SMB_workgroup=$(cat $TMPDIR/$smbhost.serverinfo | grep '<GROUP>' | awk '{ print $1 }')
	    SMB_netbiosname=$(cat $TMPDIR/$smbhost.serverinfo | grep --invert-match '<GROUP>' | awk '{ print $1 }')
	    
	    # create the mappings: path linked to the unc address
	    # note the ip= option, required by CIFS (at least on my machine)
	
    	    for SMB_share in $(cat $TMPDIR/$smbhost.sharesinfo | grep "^Disk" | cut -d "|" -f 2); do
	
		echo "\\"

		echo -n "/$SMB_workgroup/$SMB_netbiosname/$SMB_share -rw,ip=$smbhost ://$SMB_netbiosname/$SMB_share "
	    
	    done
	
	fi

    
    done
    
fi