#!/usr/bin/perl

# auto.smbbrowse -- by greenfly (greenfly@greenfly.org)
# This script will output the proper autofs configuration 
# based on the servername it is passed.

# here is an example entry in /etc/auto.master to use this script,
# the most important thing is the -nonstrict option, otherwise if a single
# smb filesystem can't be mounted as guest, none will:
# /var/autofs/smbbrowse   /etc/auto.smbbrowse     --timeout=60,-nonstrict

# once installed, to use, cd to /var/autofs/smbbrowse/server/share
# ls /var/autofs/smbbrowse/server/ will list all available shares on that server

# on debian: apt-get install libfilesys-smbclient-perl
# otherwise: perl -MCPAN -e 'install Filesys::SmbClient'
use Filesys::SmbClient; 

my $mount_options = "-fstype=smbfs,guest";


my $server = shift(@ARGV);

my $smb = new Filesys::SmbClient();

# get list of file shares
my @shares = browse("smb://$server");


# start the output
print "$mount_options\t";

foreach(@shares)
{
   s/ /\\ /g;
   print "/$_ //$server/$_ ";
}
print "\n";




#------------------------------------------------------------------------------
# Method that browse content of $rep and output the list of file shares
#------------------------------------------------------------------------------
sub browse
{
   my ($rep) = @_;
   chop($rep) if ($rep=~/\/$/);
   return undef if (!$rep);

# Read directory
   my $D = $smb->opendir($rep) || die "Can't read $rep:$!\n";
   my @f = $smb->readdir_struct($D);
   $smb->close($D);
# Sort file by name
   @f = sort { $a->[1] cmp $b->[1] } @f;

   my @ftemp;
   foreach $f (@f)
   {
# filter out everything that isn't a file share
      if($f->[0] == 3){ push @ftemp, $f->[1]; }
   }
   @f = @ftemp;

   return @f;
}
