#  Owner.pl
#  Example 3.12:
#  ----------------------------------------
#  From "Win32 Perl Scripting: Administrators Handbook" by Dave Roth
#  Published by New Riders Publishing.
#  ISBN # 1-57870-215-1
#
#  This script displays and optionally sets the owner of securable objects
#  such as files, directories and Registry keys.
#
print "From the book 'Win32 Perl Scripting: The Administrator's Handbook' by Dave Roth\n\n";


use Getopt::Long;
use Win32::Perms;

# Turn off intense domain lookups
Win32::Perms::LookupDC( 0 );

Configure( \%Config );
if( $Config{help} )
{
  Syntax();
  exit();
}

$~ = OwnerHeader;
write;
$~ = Owner;
foreach $Mask ( @{$Config{masks}} )
{
  my( @List ) = glob( $Mask );
  if( ! scalar @List )
  {
    push( @List, $Mask );
  }
  foreach $Path ( @List )
  {
    my $Perm;

    if( ! ( $Perm = new Win32::Perms( $Path ) ) )
    {
      $Owner = "Can't get permissions.\n";
    }
    else
    {
      if( "" ne $Config{owner} )
      {
        $Perm->Owner( $Config{owner} );
        $Perm->Set();
      }
      $Owner = $Perm->Owner();
    }
    write;
  }
}

sub Configure
{
  my( $Config ) = @_;
  my $Result;

  Getopt::Long::Configure( "prefix_pattern=(-|\/)" );
  $Result = GetOptions( $Config, 
                        qw(
                          owner|o|s=s
                          help|?|h
                        )
  );
  push( @{$Config->{masks}}, @ARGV );
  $Config->{help} = 1 unless( $Result &&  scalar @{$Config->{masks}} );
}

sub Syntax
{
  my( $Script ) = ( $0 =~ /([^\\\/]*?)$/ );
  my( $Line ) = "-" x length( $Script );

  print <<EOT;

$Script
$Line
Displays (and sets) the owner of securable objects.

Syntax:
    perl $Script [-s Account] Path [ Path2 ... ]
        -s Account..Set the owner to the specified account.
        Path........The path to a securable object.
                    This path can consist of ? and * wildcards.

EOT
}

format OwnerHeader =
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<
"Path", "Owner"
-------------------------------------- ----------------------------
.

format Owner =
@<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<<<<<<<<
$Path, $Owner
.
