#!/usr/local/bin/perl -w

$passwdfile = "/etc/passwd";
$groupfile  = "/etc/group";
$groupfile_out = ">/etc/group";

&mkuserlist;
&fix_group_file;

sub mkuserlist {
   $count = '0';
   (open PASSWDFILE, $passwdfile) or
      die 'failed during opening of ', $passwdfile;
   @user_list = ();
   while (<PASSWDFILE>) {
      chomp(($user_list[$count++]) = split(/:/,$_));
   };
   close PASSWDFILE;   
};

sub fix_group_file {
   &init_group_hash;
   &write_new_groupfile;
};

sub init_group_hash {
   (open GROUPFILE, $groupfile) or
      die 'failed during open of ', $groupfile;
   while (<GROUPFILE>) {
      chomp(@tmp_array = split(/:/, $_));
      $group_info = "$tmp_array[0]" . '::' . "$tmp_array[2]" . ':';
      $user_count = '0';
      GROUPMEMB: foreach $group_member (split(/,/, pop @tmp_array)) {
         foreach $user (@user_list) {
            if ($user eq $group_member) {
               if ($user_count++ == '0') {
                  $group_info = $group_info . $group_member;
               } else {
                  $group_info = $group_info . ',' . $group_member;
               };
               next GROUPMEMB;
            };
         };
      };
      push(@full_group_list, $group_info);
   };
   close GROUPFILE;
};

sub write_new_groupfile {
   (open GROUPFILE_OUT, $groupfile_out) or
      die 'failed during open of ', $groupfile_out;
   foreach $full_line ( @full_group_list ) {
      print GROUPFILE_OUT ($full_line, "\n");
   };
};
