#  Rename.pl
#  Example 2.8:
#  ----------------------------------------
#  From "Win32 Perl Scripting: Administrators Handbook" by Dave Roth
#  Published by New Riders Publishing.
#  ISBN # 1-57870-215-1
#
print "From the book 'Win32 Perl Scripting: The Administrator's Handbook' by Dave Roth\n\n";


use Getopt::Long;
use Win32::NetAdmin;
use Win32::AdminMisc;

Configure( \%Config );
if( $Config{help} )
{
  Syntax();
  exit();
}

if( "" ne $Config{domain} )
{
  # Must first assign some value to the machine key otherwise
  # GetDomainController() will fail.
  $Config{machine} = "";
  Win32::NetAdmin::GetDomainController( '', 
                                        $Config{domain}, 
                                        $Config{machine} );
}
else
{
  # Must first assign some value to the machine key otherwise
  # GetDomainController() will fail.
  if( "" eq $Config{machine} )
  {
    $Config{machine} = "";
    Win32::NetAdmin::GetDomainController( '', 
                                          Win32::DomainName(), 
                                          $Config{machine} );
  }
}

print "Renaming '$Config{machine}\\$Config{name}' to ";
print "'$Config{machine}\\$Config{new_name} ... ";
if( Win32::AdminMisc::RenameUser( $Config{machine}, 
                                  $Config{name}, 
                                  $Config{new_name} ) )
{
  print "successful.\n";
}
else
{
  my $Error =  Win32::FormatMessage( Win32::AdminMisc::GetError() );
  $Error =~ s/\r|\n//g;
  print "failed to rename: $Error\n";
}

sub Configure
{
  my( $Config ) = @_;
  
  Getopt::Long::Configure( "prefix_pattern=(-|\/)" );
  $Config->{machine} = Win32::NodeName();
  $Result = GetOptions( $Config, 
                         qw(
                             machine|m=s
                             domain|d=s
                             help|?
                         )
                     );
  
  $Config->{help} = 1 if( ! $Result );
  if( "" ne $Config->{machine} )
  {
    $Config->{machine} = "\\\\$Config->{machine}"; 
    $Config->{machine} =~ s/^(\\\\)+/\\\\/;
  }  
  $Config->{name} = shift @ARGV;
  $Config->{new_name} = shift @ARGV;
  $Config->{help} = 1 unless( "" ne $Config->{name}
                              && "" ne $Config->{new_name} );
}

sub Syntax
{
    my( $Script ) = ( $0 =~ /([^\\\/]*?)$/ );
    my( $Line ) = "-" x length( $Script );

    print <<EOT;

$Script
$Line
Renames an account.

Syntax:
    perl $Script [-m Machine | -d Domain] Account NewAccount
        -m Machine..Specify the machine the account lives on.
        -d Domain...Specify the domain the accounts live in.
        Account.....The name of the account (the userid).
        NewAccount..The new name of the account.
EOT
}

