#!/usr/bin/perl

# Program prejde cez vsetky pocitace, ktore najde na sieti
# cez smb protokol a urobi vypis zoznamu shareovanych prostriedkov.

$WorkPath = "/tmp/";
$FileNameMaster = $WorkPath."smbbrowse.master";

if( $ARGV[0]=~/^$/){
  print "\nsmbbrowse.pl\t\t\t(C)2000 by Cavo\n\nsmbbrowse.pl <name>\n\t<name> name of machine on network.\n";
  exit 1;
}

# zisti mastra v mojej skupine
system "smbclient -L $ARGV[0] -N > ".$FileNameMaster;
open FILEMaster, "<".$FileNameMaster;
$Ano = 0;
while( $LineWork = <FILEMaster>){
  if( $LineWork=~/(\w+)\s+(\w+)/ && $Ano==1 && $1!=~/-+/){
    $Master = $2;
#    print "Check Masters: Workgroup:", $1, "\tMaster:", $2, "\n";
  }
  if( $LineWork=~/Workgroup/) {
    $Ano=1;
  }
}
close FILEMaster;

# zisti ostatnych mastrov vo vsetkych skupinach, ktore pozna
system "smbclient -L $Master -N > ".$FileNameMaster;
open FILEMaster, "<".$FileNameMaster;
$Ano = 0;
while( $LineWork = <FILEMaster>){
  if( $LineWork=~/(\w+)\s+(\w+)/ && $Ano==1 && $1!=~/-+/){
    push @Workgroups, $1;
    push @Masters, $2;
#    print "Workgroup:", $1, "\tMaster:", $2, "\n";
  }
  if( $LineWork=~/Workgroup/) {
    $Ano=1;
  }
}
close FILEMaster;

#zisti pocitace v skupinach
foreach( @Masters){
  $Master=$_;
  $Ano=0;
  system "smbclient -L $Master -N > $FileNameMaster";
  open FILEMaster, "<$FileNameMaster";
  while( $LineWork = <FILEMaster>){
    if( $Ano==1 && $LineWork=~/Workgroup/){
      $Ano=0;
    }
    if( $LineWork=~/(\w+)/ && $Ano==1 && $1!=~/-+/){
      push @Machine, $1;
#      print "Machine: ", $1, "\n";
    }
    if( $LineWork=~/Server\s+Comment/){
#      print "Nastavujem 1 pre $Master\n";
      $Ano=1;
    }
  }
  close FILEMaster;
}
unlink $FileNameMaster;

#vypise zoznam zdielanych prostriedkov
foreach( @Machine){
  $Machine=$_;
  $Ano=0;
#  system "nmblookup $_";
  print "Machine: $_\n";
  system "smbclient -L $Machine -N > $FileNameMaster";
  open FILEMaster, "<$FileNameMaster";
  while( $LineWork = <FILEMaster>){
    if( $Ano==1 && $LineWork=~/Server\s+Comment/){
      $Ano=0;
    }
    if( $LineWork=~/(\w+)\s+Disk/ && $Ano==1 && $1!~/-+/){
      push @ShareName, $1;
      print "ShareName: ", $1, "\n";
      $sharestr = "echo \"recurse\nls\nquit\" | smbclient //$Machine/$1 -N > /tmp/$Machine.$1.ls-R";
      system $sharestr;
    }
    if( $LineWork=~/Sharename\s+Type\s+Comment/){
      $Ano=1;
    }
  }
  close FILEMaster;
}
unlink $FileNameMaster;


