#  DomSync.pl
#  Example 2.10:
#  ----------------------------------------
#  From "Win32 Perl Scripting: Administrators Handbook" by Dave Roth
#  Published by New Riders Publishing.
#  ISBN # 1-57870-215-1
#
#  This script initiates domain synchronizations.
#
#
print "From the book 'Win32 Perl Scripting: The Administrator's Handbook' by Dave Roth\n\n";


use Getopt::Long;
use Win32::Lanman;

Configure( \%Config );
if( $Config{help} )
{
  Syntax();
  exit( 0 );
}

if( $Config{full_sync} )
{
  my $Pdc;
  if( Win32::Lanman::NetGetDCName( $server, $Config{domain}, \$Pdc ) )
  {
    my %Info;
    if( Win32::Lanman::LogonControlPdcReplicate( $Pdc, \%Info ) )
    {
      print "Successfully initiated a full domain synchronization ";
      print "for the $Config{domain} domain.\n";
    }
    else
    {
      print "Full domain synchronization for the $Config{domain} "
            . "domain failed.\n";
      print "Error: " . Win32::Lanman::GetLastError() . "\n";
    }
  }
  else
  {
    print "Unable to locate the primary domain controller for the "
          . "domain $Config{domain}\n";
    print "Error: " . Win32::Lanman::GetLastError() . "\n";
  }
}
else
{
  print "Synchronizing the following domain controllers with its PDC:\n";
  foreach my $Server ( @{$Config{servers}} )
  {
    my %Info;
    my $Result = Win32::Lanman::LogonControlSynchronize( $Server, 
                                                         \%Info );
    printf( "  %-20s %s\n", 
            $Server, 
            ( $Result )? "successful" : "failed" );
  }
}

sub Configure
{
  my( $Config ) = @_;

  Getopt::Long::Configure( "prefix_pattern=(-|\/)" );
  $Result = GetOptions( $Config, 
                          qw(
                              full_sync|f
                              help|?
                          )
                      );
  $Config->{help} = 1 if( ! $Result );
  if( $Config->{full_sync} )
  {
    $Config->{domain} = shift @ARGV;
    $Config->{domain} = Win32::DomainName() 
                      if( "" eq $Config->{domain} );
  }
  else
  {
    push( @{$Config->{servers}}, @ARGV );
  }
  if( ( ! $Config->{full_sync} ) && ( ! scalar @{$Config->{servers}} ) )
  {
    $Config->{help} = 1;
  }
}

sub Syntax
{
  my( $Script ) = ( $0 =~ /([^\\\/]*?)$/ );
  my( $Line ) = "-" x length( $Script );

  print <<EOT;

$Script
$Line
Initiates synchronizations between domain controllers.

Syntax:
    perl $Script -f [Domain] | Server [ Server2 ...]
        -f [Domain] Performs a full domain synchronization.
                    This will default to the local user's domain unless
                    the optional Domain is specified.
        Server......Specifies a BDC to synchronize with its PDC.
EOT
}

