#!/usr/bin/perl -w

use strict;
use File::stat;
use Data::Dumper;

my @files = @ARGV;
my $DEBUG = 1;

my $filelist = {};

print @files if ($DEBUG>2);

foreach my $file (@files) {
    my $sb = lstat $file;
    my $inode = {};
    $inode->{'uid'}   = $sb->uid;
    $inode->{'gid'}   = $sb->gid;
    $inode->{'perm'}  = $sb->mode & 07777;
    $inode->{'uname'} = getpwuid($sb->uid);
    $inode->{'gname'} = getgrgid($sb->gid);
    
    $filelist->{$file} = $inode; #copy hash

    if ($DEBUG > 2) {
        printf "Permissions are %04o\n", ($inode->{'mode'}) & 07777;
        print "$file: mode: " . $inode->{'perm'} .
              " [" . $inode->{'uid'} . "," .
        $inode->{'gid'} . "]\n";
        print "    " . $inode->{'uname'} . ":" .
        $inode->{'gname'} . "\n";
    }
    #numeric:
    #printf "chmod %04o $file ; chown %d:%d $file\n", 
    #    $perm, $inode->uid, $inode->gid;
    #symbolic:
    if ($DEBUG > 1) {
        printf "chmod %04o %s ; chown %s:%s %s\n", 
            $inode->{'perm'}, $inode->{'file'},
            $inode->{'uname'}, $inode->{'gname'}, $inode->{'file'};
    }
}

#save:
open (FILELIST, ">filelist.dump")
    or die "open (rw) filelist.dump failed [$!]\n";
print FILELIST Data::Dumper->Dump(  [$filelist], ['$filelist']);
close (FILELIST);

#clear (delete) filelist:
$filelist = {};

#load:

open (FILELIST, "filelist.dump")
    or die "open (ro) filelist.dump failed [$!]\n";

#load filelist (DANGEROUS - this is not safe at all):
eval (join("", <FILELIST>));
close (FILELIST);

#filelist is restored from disk
foreach my $file (keys %$filelist) {
    my $inode = $filelist->{$file};
    printf "chmod %04o %s ; chown %s:%s %s\n", 
        $inode->{'perm'}, $file,
        $inode->{'uname'}, $inode->{'gname'}, $file;
}

