#!/usr/bin/perl
sub init {
	$min = 1;
	$max = 15;
	$smbdir = "/mnt/smb";
	$autodir = "/var/smb";
	$afsfile = "/etc/autofs/auto.smb";
	$ip = "192.168.0";
	$log = "/var/log/smbbrowser";
	if( ! system( "cat /tmp/smbbrowser 2>&1 >/dev/null" ) )
	{
		exit 0;
	}
	system( "touch /tmp/smbbrowser >/dev/null" );
};

sub scan {
	my $n = 0;
	for ($i=$min; $i <= $max; $i++ ) {
		$list[$n]="$ip.$i";
		$n++;
	};
};

sub scanshare {
	my $host = shift;
	$host =~ s/~[\d.]//g;
	print logi $host,"\n";
	open( com, "source /etc/profile; smbclient -N -L $host 2>/dev/null |" );
	my @output = <com>;
	close( com );
	open( p, ">/tmp/$host.smb" );
	foreach (@output) {
		my $line = $_;
		if( $line =~ /Disk/ ) {
			$line =~ s/\s*Disk.*$//;
			$line =~ s/^\s*//;
			$line =~ s/^$\n//;
			if ( ! ($line =~ /\$$/) ) {
				print p $line;
				print logi $line;
			};
		};
	};
	close( p );
};

sub autofsfile {
	system( "cat $afsfile.static > $afsfile 2>/dev/null" );
	open( OUT, ">$afsfile" );
	foreach (@list) {
		my $hostname = $_;
		scanshare $hostname;
		#print $hostname,":\n";
		open( IN, "</tmp/$hostname.smb" );
		my @lines = <IN>;
		foreach (@lines) {
			my $line = $_;
			$line =~ s/\ /\\\ /g;
			$line =~ s/\n$//;
			$wline = "$hostname\_$line\t-fstype=smbfs,uid=samba,gid=samba,fmask=770,dmask=770,credentials=/root/hasla\t://$hostname/$line";
			$wline =~ s/\n//g;
			print OUT $wline,"\n";
		};
		close(IN);
	};
	close(OUT);
};

sub links {
	system( "rm -rf $smbdir/* >/dev/null" );
	foreach (@list) {
		my $host = $_;
		$host =~ s/\n//;
		if ( ! system( "ls -l /tmp/$host.smb | grep -v -e ' 0 ' >/dev/null" ) ) {
			system( "mkdir $smbdir/$host >/dev/null" );
		};
		open( IN, "</tmp/$host.smb" );
		my @lines = <IN>;
		foreach (@lines) {
			my $line = $_;
			$line =~ s/\ /\\\ /g;
			$line =~ s/\n$//;
			my $source = $autodir;
			$source .= "/";
			$source .= $host;
			$source .= "_";
			$source .= $line;
			print logi "`","ln -s $source $smbdir/$host/$line","'\n";
			system( "ln -s $source $smbdir/$host/$line >/dev/null" );
		};
		close( IN );
	};
};

sub hostnames {
	
};

#-----------------------------------------
#@list = ("localhost");
my @list;

init;

open( logi, ">>$log" );

scan;

autofsfile;

links;

if( system( "kill -HUP `ps w -C automount | grep smb | cut -c -5` 2>&1 >/dev/null" ) ) {
#system( "/etc/init.d/autofs restart >/dev/null" );
		system( "/etc/init.d/autofs stop >/dev/null" );
		system( "/etc/init.d/autofs zap >/dev/null" );
		system( "/etc/init.d/autofs start >/dev/null" );
#	};
};

system( "rm /tmp/smbbrowser >/dev/null" );
close( logi );

#debug lines:
#my $cos = "192.168.0.11";
#scanshare $cos;
#system("cat /tmp/192.168.0.11.smb" );


