#!/bin/bash

# This file must be executable to work! chmod 755!

key="$1"

FILESYSTEM="cifs"

if [ "$FILESYSTEM" = "cifs" ]; then

    for P in /bin /sbin /usr/bin /usr/sbin
    do
	if [ -x $P/nmblookup ]
	then
		NMBLOOKUP=$P/nmblookup
		break
	fi
    done

    [ -x $NMBLOOKUP ] || exit 1
    
    ipaddress=$($NMBLOOKUP $key --debug-level=0 2>>/dev/null | grep '<00>' | awk '{ print $1 }')

    if [ -z "$ipaddress" ]; then

	exit 1
    
    fi
    
    opts="-fstype=cifs,guest,ip=$ipaddress"
    
    
else

    opts="-fstype=$FILESYSTEM,guest"
    
fi

for P in /bin /sbin /usr/bin /usr/sbin
do
	if [ -x $P/smbclient ]
	then
		SMBCLIENT=$P/smbclient
		break
	fi
done

[ -x $SMBCLIENT ] || exit 1

$SMBCLIENT -gNL $key 2>/dev/null| awk -v key="$key" -v opts="$opts" -F'|' -- '
	BEGIN	{ ORS=""; first=1 }
	/Disk/	{
		  if (first)
			print opts; first=0
		  dir = $2
		  loc = $2
		  # Enclose mount dir and location in quotes
		  # Double quote "$" in location as it is special
		  gsub(/\$$/, "\\$", loc);
		  print " \\\n\t \"/" dir "\"", "\"://" key "/" loc "\""
		}
	END 	{ if (!first) print "\n"; else exit 1 }
	'

