#!/usr/bin/perl -s


####file_stat#########################################################
# This sub-program returns a group id from a 13 element list given
# by the lstat function.  lstat returns the stats of files and not
# files pointed to by symbolic links.
#
# INPUT:        file name in this directory
# OUTPUT:       group id of this file
# DEPENDENCIES: be sure that you are currently in the directory
#               that this file is in.
# DATE:         April 2, 2001
# AUTHOR:       William Martin
#####################################################################

sub file_stat {
        my($file) = @_;
	my($dev,   $ino,   $mode,  $nlink,
              $uid,   $gid,   $rdev,  $size,
              $atime, $mtime, $ctime, $blksize,
              $blocks) = lstat($file);

	return ($uid, $gid);
}
#####################################################################
#####dir_scan########################################################
# This sub-program opens the users directory ($dir) and changes all
# the files that belong to the group specified by $id_to_change.  It
# then changes all the files to belong to the group specified by $id.
# This sub-program recurses throu the tree from the users home
# directory obtained from the passwrd file.
#
# INPUT:        users home directory, group id to change,
#               new group id, old uid
# OUTPUT:       All filles in the users home directory are changed
#               to belong to the new group id if they were prevously
#               owned by the $id_to_change group.
# DEPENDENCIES: sub file_stat
# DATE:         March 26, 2001
# AUTHOR:       William Martin
#####################################################################

sub dir_scan{
   my ($dir, $id_to_change, $id, $oid) = @_;
   use Cwd;

   chdir($dir) or die "Cant change to $dir:$!\n";
   opendir(DIR, ".") or die "Can't open $dir:$!\n";
   my @names = readdir(DIR) or die "Can't read $dir:$!\n";
   closedir(DIR);

   foreach my $name (@names){
      next if ($name eq "..");
      ($usr_id, $grp_id) = &file_stat($name);

      if ($usr_id == $oid){
         chown($id, $grp_id, $name);
      }

      if ($name eq "."){
          if ($grp_id == $id_to_change){
             system ("chgrp", "-h", "$id", "$name");
          }
          next;
      }

      if (-d $name && !-l $name){
         if ($grp_id == $id_to_change){
            system ("chgrp -h $id \'$name\'");;
         }

         my $bookmark = &cwd; #we must mark our spot before recursing
         &dir_scan($name, $id_to_change, $id);
         chdir($bookmark) or die "Cant change to $bookmark:$!\n";
         next;
      }

      if ($grp_id == $id_to_change){
         system ("chgrp", "-h", "$id", "$name");
      }
   }
}

#####################################################################
#MAIN################################################################

&dir_scan("/usr/users/mart1885", 100, 10000, 415);

#THIS PROGRAM IS A TEST DRIVER