#!/usr/bin/perl
#
# ol-macro-expand.pl - expand OpenLDAP schema OID macros
#
# Copyright 2006, NetAuth Consulting Ky
#
# 9 APR 2006, NetAuth Consulting
#
# License: GPLv2
#

use strict;

my @lines = <>;

my %identifiers;
my %search;
my %serialized;

# first pass
for (@lines)
{
    if (/^objectIdentifier/)
    {
        my ($first, $second, $third) = split(/ /, $_);
        chomp $third;

        # find the root oid
        if ($third =~ /^[\d|\.]+?$/)
        {
            $search{$second}      = $third;
            $serialized{$second}  = $third;
        }
        else
        {
            $identifiers{$second} = $third;
        }
    }
}

for (my $i = 0; $i < 10; $i++)
{

for my $search_key (keys %search)
{
    for my $identifier_key (keys %identifiers)
    {
        if ($identifiers{$identifier_key} =~ /$search_key/)
        {
            my $tmp = $identifiers{$identifier_key};
            $tmp    =~ s/$search_key:/$search{$search_key}\./;
            $serialized{$identifier_key} = $tmp;
            $search{$identifier_key}     = $tmp;
            delete $identifiers{$identifier_key};
        }
    }
}

}

my $outfile = "./replaced.tmp";
open(FILE, ">$outfile") || die "can't open $outfile $!";

for (@lines)
{
    if (/^\s*?attribute[tT]ype/ || /^\s*?object[cC]lass/)
    {
        $_ =~ s/^\s*//;

        if (/\([\s\t]+?(\D+?)$/)
        {
            my $tmp = $1;
            $tmp    =~ s/\s+//;
            s/$tmp/$serialized{$tmp}/;
        }
    }
}

print FILE @lines;
close FILE;

