#!/usr/bin/perl -w
#
# Clone shares from one machine to another.
#
# uses a credentials file called "cred" in the current dir, ignores
# username and password params.
use strict;
use IPC::Open3;

$| = 1;

my ( $user, $password, $server, $me ) = @ARGV;

die "usage: $0 user pass srv me" unless $user;
die "usage: $0 user pass srv me" unless $password;
die "usage: $0 user pass srv me" unless $server;
die "usage: $0 user pass srv me" unless $me; # my netbios name

print STDERR "Getting share list from $server...";
my @shares_enum = `rpcclient -A cred -d 0 -c "netshareenum" $server`;
print STDERR  "done.\n";

print STDERR  "Parsing shares list...\n";
my @shares;
my %share;
for my $line ( @shares_enum ) {
  next if $line =~ /^\s*$/;
  chomp( $line );
  my ( $field, $data ) = $line =~ m{^\s*([^:]+):\s+(.*)$};

  # XXX this isn't an obvious enough error if something does go wrong
  # We should probably bail out earlier.
  die "Failed on $line\n" if !defined( $field );

  # netname is the first field of each share, so use it as a 'flag' to
  # save info.
  if ( $field eq 'netname' ) {
	if ( %share ) {
	  print STDERR  "  " . $share{'netname'} . "\n";
	  my %bits = map { $_ => $share{$_} } keys %share;
	  my $bitsref = getsharedetails( \%bits );
	  push @shares, $bitsref if $share{'path'} =~ /\\/;	# if it's not a printer
	  # reset hash
	  undef %share;
	}
  }
  $share{ $field } = $data;
}
print STDERR  "Done with parsing.\n";

for my $share ( @shares ) {
  print STDERR "Cloning " . $share->{'netname'} ."\n";
  print "[" . $share->{'netname'} . "]\n";

  # if there's a slash in it, it's a fileshare
  if ( $share->{'path'} =~ /\\/ ) {
	# Need a drive-letter mapping FIXME
	$share->{'path'} =~ s|^(.):|\L/home/$1_drive|g;
	# flip slashes
	$share->{'path'} =~ s|\\|/|g;

	print " path = " . $share->{'path'} . "\n";
  } else {
	print " path = /var/spool/samba\n printable = yes\n";
	# do printer cloning stuff here?
  }

  print " comment = " . $share->{'remark'} . "\n" if $share->{'remark'};
  print " read only = no\n public = yes\n";

  print "\n";
}

sub getsharedetails {
  my $bitsref = shift;

  $bitsref;
}
