#  DumpPerms.pl
#  Example 4.5:
#  ----------------------------------------
#  From "Win32 Perl Scripting: Administrators Handbook" by Dave Roth
#  Published by New Riders Publishing.
#  ISBN # 1-57870-215-1
#
#  This script makes a backup of permissions.
#  Example_4_5.pl uses this resulting configuration file to recreate
#  the permissions.
#
print "From the book 'Win32 Perl Scripting: The Administrator's Handbook' by Dave Roth\n\n";


use Win32::Perms;

$DELIMITER = ";";
push( @ARGV, "*.*" ) if( 0 == scalar @ARGV );
foreach my $Mask ( @ARGV )
{
    if( $Mask =~ /[*?]/ )
    {
        push( @Paths, glob( $Mask ) );
    }
    else
    {
        push( @Paths, $Mask );
    }
}

foreach my $Path ( @Paths )
{
    print STDERR "$Path ";
    if( ! ProcessPath( $Path ) )
    {
        print STDERR "...FAILED!\n";
    }
    print STDERR "\n";
}
                
sub ProcessPath
{
    my( $Path ) = @_;
    my @Acl;
    my $Perm;
    
    return( 0 ) unless( $Perm = new Win32::Perms( $Path ) );
    print "[$Path]\n";
    $Perm->Dump( \@Acl );
    foreach my $Ace ( @Acl )
    {
        my $Account = $Ace->{Account};
        $Account = $Ace->{Domain} . "\\" . $Account if( "" ne $Ace->{Domain} );
        if( "Group" eq $Ace->{Entry} || "Owner" eq $Ace->{Entry} )
        {
            print "$Ace->{Entry}=$Account\n";
        }
        else
        {
            my( @MaskPerms, @FriendlyPerms, @Flags );
            print "$Ace->{Entry}=";
            Win32::Perms::DecodeMask( $Ace, \@MaskPerms, \@FriendlyPerms );
            Win32::Perms::DecodeFlag( $Ace->{Flag}, \@Flags );

            print join( $DELIMITER, ( $Account, $Ace->{Access},
                        join( "|", @Flags ),
                        join( "|", @MaskPerms ) ) );
            print "\n";
        }
    }
    print "\n";
    return( 1 );
}

