#! /usr/bin/perl
# Compare two Red Hat comps files (given as command line args)
if ($#ARGV = 2 ) {
  $tmpdir=@ARGV[2];
} else {
  $tmpdir="/tmp/cmptst";
}
  if ($#ARGV <= 1 ) {
	print STDERR (" usage - comp.pl <comp file 1> <comp file 2> <tmpdir>\n");
        exit 1;
    }
# set up our subdirs
  mkdir ("$tmpdir",0777);
  mkdir ("$tmpdir/CF1",0777);
  mkdir ("$tmpdir/CF2",0777);
  unlink <$tmpdir/CF1/*>;
  unlink <$tmpdir/CF2/*>;
  
sub split_comp {
 local ($CFDIR,$INFIL) = @_;
  open (INFIL,$INFIL) || die (" $INFIL not found\n");
  $startf = 0;
  while (<INFIL>) {
    chop $_;
    $_ =~ s/\//./g;
    ($n,$a,$b,$c,$d) = split();
      if (($n eq "0") || ($n eq "1")) {
        if ($startf == 0) {
         $startf=1;
         if ($a eq "") { $a="f1"; }

         open(OUTFILE,">$tmpdir/$CFDIR/$n.$a$b$c$d") || die ("Couldn't open $tmpdir/$CFDIR/$a$b$c$d");
	  }
       else { die ("I'm lost, sorry.\n"); }
     }
     else {
       if ( ($n eq "end") || ($n eq "")) {
         close OUTFILE;
         $startf=0;
         }
      else  {
       print OUTFILE "$n$a$b$c$d\n";
            }
	}
   }
   close INFIL;
}

sub check_diffs {
  foreach $file (@_) {
   if ( -f "$tmpdir/CF2/$file" ) {
     open (IN1,"$tmpdir/CF1/$file");
     open (IN2,"$tmpdir/CF2/$file");
     read (IN1, $buf1, 2048); 
     read (IN2, $buf2, 2048); 
     close IN1;
     close IN2;
   if ($buf1 ne $buf2 ) {
     print "$file is different\n";
     }
   else {
     print "$file is the same\n";
     }
  }
  }
}

split_comp("CF1",@ARGV[0]);
split_comp("CF2",@ARGV[1]);

# Now compare files between the two directories ...

opendir(DIR1,"$tmpdir/CF1") || die ("whoops! CF1 dir\n");
opendir(DIR2,"$tmpdir/CF2") || die ("whoops! CF2 dir\n");
@list1 = grep !/^\.\.?$/, readdir(DIR1);
@list2 = grep !/^\.\.?$/, readdir(DIR2);
closedir DIR1;
closedir DIR2;
$l1 = join($",@list1);
$l2 = join($",@list2);
if ($l1 eq $l2 ) {
# all files the same
  check_diffs(@list1);
}
else {
# Print a list of which groups are where
 print "*******\n";
 @slist1 = sort (@list1);
 @slist2 = sort (@list2);
 $b=0;
 for ($a=0; $a<=@slist1; $a++)
 {
   if ( @slist1[$a] lt @slist2[$b] )
    {
     print @slist1[$a]," is not in ",@ARGV[1],"\n";
     }
    elsif ( @slist1[$a] gt @slist2[$b] )
      {
        print @slist2[$b]," is not in ",@ARGV[0],"\n";
        $a = $a - 1;
        $b = $b + 1;
       }
     else {
        print @slist2[$b]," is in BOTH\n";
        $b = $b + 1;
      }
  }
  print "*******\n";
  check_diffs(@list1);
}
# Cleanup
#  unlink <$tmpdir/CF1/*>;
#  unlink <$tmpdir/CF2/*>;
#  rmdir ("$tmpdir/CF1");
#  rmdir ("$tmpdir/CF2");
