#!/usr/bin/perl
# This little script record permissions and creates a shell script to replicate these permissions on any machine where those same files exist.
# This was created by our Lord and Master EE.

sub do_recursive_dir($) {
    my @files;
    my $file;
    my $dir = shift;

    print "# do recursive called with $dir\n";
    opendir(DIR, $dir) || do { 
        print STDERR "Couldn't open directory $dir\n";
        return;
    };
    @files = readdir(DIR);
    closedir(DIR);
    foreach $file (@files) {
        next if $file eq ".";
        next if $file eq "..";
        my $filename = $dir."/".$file;
        my @info = lstat($filename);
        my $mode = sprintf("%o", $info[2]);
        $mode =~ s/^.*?0(.*)$/$1/;
        printf "if [ -e %s ]; then chmod 0%s %s; fi\n", $filename, 
        $mode, $filename;
        if ( -d $filename ) { do_recursive_dir($filename); }
    }
}

print "#!/bin/sh\n";
@where = qw(/usr/bin /usr/lib /etc /bin /sbin /usr/sbin /lib);
foreach $dir (@where) {
    print "# getting permissions for $dir\n";
    @info = lstat($dir);
    $mode = sprintf("%o", $info[2]);
    $mode =~ s/^.*?0(.*)$/$1/;
    printf "if [ -e %s ]; then chmod 0%s %s; fi\n", $dir, $mode, $dir;
    printf "if [ -e %s ]; then chown %s:%s %s; fi\n", $filename, $info[4], $info[5], $filename;
    do_recursive_dir($dir);
}
