#!/usr/bin/perl -w
#
#Utility to find duplicate GUIDs when given LDIF input.

#Define the application.
my($appBinaryFile) = `echo $0`;
chomp($appBinaryFile) if(length($appBinaryFile) > 0);
#If the user asks how to do stuff, let them know.
if(defined($ARGV[0]))
{
  if(($ARGV[0] =~ /\-help/) || ($ARGV[0] eq '/?'))
  {
    print "\n" . 'Usage: ' . $appBinaryFile . ' <guidLDIFFileName>' . "\n";
    print '<guidLDIFFileName> should hold the output from a command like the following: ' . "\n\n" . 'ldapsearch -h 123.45.67.89 -p 389 -D cn=admin,dc=users,dc=system -x -W guid > guidldif.ldif' . "\n\n" . 'Later run: ' . $appBinaryFile . ' guidldif.ldif' . "\n\n"; 
    exit;
  }#End if
}#End if
else
{
  print 'Please provide a filename to process.' . "\n\n";
  exit;
}#End else

#Create some variables.
my($appVersion) = '0.0001.2005-11-21'; #Increment over time as features change.
my($appAuthor) = 'Aaron Burgemeister';
my($appAuthorEmail) = 'ab@novell.com;dajoker@gmail.com';
my($appRuntimeParams) = join(' ', @ARGV);

#Get the file to read in.
my(%guidHash) = ();
my($inputFile) = shift(@ARGV);
my(@inputData) = readFile($inputFile);
@inputData = cleanCRs(@inputData);
my($oneline) = '';
my($thisObjectDN) = '';
my($thisObjectGUID) = '';
my($key0) = '';
my($ctr0) = 0;
my($totalDupeGuidCount) = 0;

#Loop through the input data.
while($oneLine = shift(@inputData))
{
  chomp($oneLine);

  if($oneLine =~ /^dn: (.+)$/)
  {
    $thisObjectDN = $1;
  }#End if
  elsif($oneLine =~ /^GUID:: (.+)$/i)
  {
    $thisObjectGUID = $1;
    push(@{$guidHash{$thisObjectGUID}{'dn'}}, $thisObjectDN);
    ++$guidHash{$thisObjectGUID}{'count'};
  }#End elsif
}#End while

foreach $key0 (keys(%guidHash))
{
  #If there is more-than one DN associated, do stuff (print DN count and all
  #DNs).
  if($guidHash{$key0}{'count'} > 1)
  {
    print $key0 . ' - count: ' . $guidHash{$key0}{'count'} . "\n";
    #Print all DNs.
    while($ctr0 < scalar(@{$guidHash{$key0}{'dn'}}))
    {
      print '  ' . $guidHash{$key0}{'dn'}[$ctr0] . "\n";
      ++$ctr0;
    }#End while
    print "\n";
    ++$totalDupeGuidCount;
    $ctr0 = 0;
  }#End if
}

print "\n\n" . 'You had ' . $totalDupeGuidCount . ' duplicate GUIDs.' . "\n\n";

#All done.
exit;






#Method to clean an array of carriage-returns.
sub cleanCRs
{
  my(@inLineArray) = @_;
  my(@outLineArray) = ();
  my($line) = '';

  #Read each line and clean it.
  while($line = shift(@inLineArray))
  {
    $line =~ s/\r+//;
    push(@outLineArray, $line);
  }#End while

  return (wantarray ? @outLineArray : \@outLineArray);
}



#Method to read a file into an array and then return that array.
sub readFile
{
  my($file) = shift(@_);
  open(F, "< $file") or die('Can\'t open ' . $file . ': ' . $!);
  my(@lines) = <F>;
  close F;
  return (wantarray ? @lines : \@lines);
}

