#!/usr/bin/perl

sub oidcmp
{
  @oid1arr = split (/\./,$a);
  @oid2arr = split (/\./,$b);

  if (@oid1arr < @oid2arr)         # comparing oidlengths
  {
    $min_len = @oid1arr;
  }
  else  { $min_len = @oid2arr; }

  for(my $k = 0; $k< $min_len; $k++)
  {
    if(int($oid1arr[$k]) < int($oid2arr[$k])) { return (-1); }
    if(int($oid1arr[$k]) > int($oid2arr[$k])) { return (1); }
  }
  if (@oid1arr < @oid2arr) { return (-1); }
  if (@oid1arr > @oid2arr) { return (1); }
  print "oids are equal! redifinition?\n";
  return 0;
}

sub sibling  # assumed $oid1line and $oid2line are oidlines with equal oidlengths
{
  my @oid1 = split (/\./,$oid1line);
  my @oid2 = split (/\./,$oid2line);
  for ($p=0; $p<$#oid1; $p++)  # compare all but last component
  {
    if(int($oid1[$p]) != int($oid2[$p])) { return int(0); }
  }
  return int(1);
}

open(INFILE,$ARGV[0]) or die $!;
$firstline = 0;               # inside first line of new definition
$flag = 0;                    # looking for ::=
$descflag = 0;                # found  DESCRIPTION clause
$desccont = 0;                # inside DESCRIPTION clause
$contflag = 0;                # found  CONTACT-INFO clause
$contcont = 0;                # inside CONTACT-INFO clause
while(<INFILE>)
{
  @items = split(/\s+/,$_); # if space at head, $items[0] == ""

  if( $items[0] )
  {
    last if /^END$/;
    next if /^IMPORTS/;
    next if /^--/;
    $token1 = $items[0];
    $token2 = $items[1];
    $token3 = $items[2];
    $token4 = $items[3];
    $token5 = $items[4];
    $token6 = $items[5];
    $firstline = 1;
    $flag = 1;
  }

  if( ($items[0] eq "") && $items[1] )
  {
    $token1 = $items[1];
    $token2 = $items[2];
    $token3 = $items[3];
    $token4 = $items[4];
    $token5 = $items[5];
    $token6 = $items[6];
    if($flag==0)
    {
      $firstline = 1;
    }
    $flag = 1;
  }

  if($firstline == 1)
  {
    $name = $token1;
    if(($token2 eq "DEFINITIONS") && ($token3 eq "::=") && ($token4 eq "BEGIN"))
      { $tab_title = $token1; $flag = 0; $contactcont = 0; } # no sense to look for oid

    if(($token2 eq "::=") && ($token3 eq "TEXTUAL-CONVENTION")) { $flag = 0; } # no sense to look for oid

    if( $token2 eq "MODULE-IDENTITY")
      { $types{$name} = $token2; }
    if(($token2 eq "OBJECT") && ($token3 eq "IDENTIFIER"))
      { $types{$name} = "OBJECT_IDENTIFIER"; $contactcont = 0; }
    if( $token2 eq "OBJECT-TYPE")
      { $types{$name} = $token2; }
    if( $token2 eq "NOTIFICATION-TYPE")
      { $types{$name} = $token2; }
    if( $token2 eq "MODULE-COMPLIANCE")
      { $types{$name} = $token2; }
    if( $token2 eq "OBJECT-GROUP")
      { $types{$name} = $token2; }
    if( $token2 eq "NOTIFICATION-GROUP")
      { $types{$name} = $token2; }
    $firstline = 0;
  }

  if( ($desccont==0) && ($contcont==0) && (int($#items)==-1) )
    {
#       print "got empty line (not inside DESCRIPTION or CONTACT-INFO clause) after ",$name,"\n";
       $flag = 0; # stop searching oid for $name; probably this was not a node in mib tree
    }

# syntax clause ( assumed that textual description can begin either in current line or at next line )
  if(($token1 eq "SYNTAX") && $flag)
    { if(!$syntax{$name})
      {
        $syntflag = 1;
	for($s=2; ($s<=$#items)&&(!($items[$s] =~ /{.*$/ )); $s++)
	  { $short_syntax{$name} = $short_syntax{$name}.$items[$s]." "; }
      }
    }
  if($syntflag && ($items[$#items]=~ /{$/)) { $syntcont = 1; }
  if($syntflag && !$syntax{$name})
  {
    for($s=2; $s<=$#items; $s++)
    {
      $syntax{$name} = $syntax{$name}.$items[$s]." ";
    }
    $syntflag = 0;
  }
  else
  {
    if($syntcont)
    {
      for($s=1; $s<=$#items; $s++)
      {
        $syntax{$name} = $syntax{$name}.$items[$s]." ";
      }
      if($items[$#items] =~ /}.*$/) { $syntcont = 0; }
    }
  }

# MAX-ACCESS clause  ( assumed that textual description is always next token in current line )
  if(($token1 eq "MAX-ACCESS") && $flag) { $access{$name} = $token2; }

# DESCRIPTION clause  ( assumed that textual description will always begin at next line )
  if(($token1 eq "DESCRIPTION") && $flag) { $descflag = 1; }
  if(($descflag==1) && ($desccont==0) && ($items[1]=~ /^"/)) # DESCRIPTION text started
  {
    if(!$desc{$name}) { $desccont = 1; $descflag = 0; }
  }
  if($desccont==1)
  {
    $desc{$name} = $desc{$name}.$_;
  }
  if(($desccont==1) && ($items[$#items]=~ /".*$/)) # DESCRIPTION text finished
  {
    $desccont = 0; $descflag = 0;
  }

# OBJECTS clause under OBJECT-GROUP
  if(($token1 eq "OBJECTS") && $flag && ($types{$name} eq "OBJECT-GROUP")) { $ogrpflag = 1; }
  if(($ogrpflag==1) && ($ogrpcont==0) && ($items[$#items]=~ /{$/)) # OBJECT-GROUP text started
  {
    if($objgrp{$name} eq "") { $ogrpcont = 1; $ogrpflag = 0; }
  }
  if($ogrpcont==1)
  {
    $objgrp{$name} = $objgrp{$name}.$_;
    $objgrp{$name} =~ s/OBJECTS//;
  }
  if(($ogrpcont==1) && ($items[$#items]=~ /}$/)) # OBJECT-GROUP text finished
  {
    $ogrpcont = 0; $ogrpflag = 0;
  }

# NOTIFICATIONS clause under NOTIFICATION-GROUP
  if(($token1 eq "NOTIFICATIONS") && $flag && ($types{$name} eq "NOTIFICATION-GROUP")) { $ngrpflag = 1; }
  if(($ngrpflag==1) && ($ngrpcont==0) && ($items[$#items]=~ /{$/)) # NOTIFICATION-GROUP text started
  {
    if($ntfgrp{$name} eq "") { $ngrpcont = 1; $ngrpflag = 0; }
  }
  if($ngrpcont==1)
  {
    $ntfgrp{$name} = $ntfgrp{$name}.$_;
    $ntfgrp{$name} =~ s/NOTIFICATIONS//;
  }
  if(($ngrpcont==1) && ($items[$#items]=~ /}$/)) # NOTIFICATION-GROUP text finished
  {
    $ngrpcont = 0; $ngrpflag = 0;
  }

# OBJECTS clause under NOTIFICATION-TYPE
  if(($token1 eq "OBJECTS") && $flag && ($types{$name} eq "NOTIFICATION-TYPE")) { $ntflag = 1; }
  if(($ntflag==1) && ($ntcont==0) && ($items[$#items]=~ /{$/)) # NOTIFICATION-TYPE text started
  {
    if($ntf{$name} eq "") { $ntcont = 1; $ntflag = 0; }
  }
  if($ntcont==1)
  {
    $ntf{$name} = $ntf{$name}.$_;
    $ntf{$name} =~ s/OBJECTS//;
  }
  if(($ntcont==1) && ($items[$#items]=~ /}$/)) # NOTIFICATION-TYPE text finished
  {
    $ntcont = 0; $ntflag = 0;
  }

# CONTACT-INFO clause  ( assumed that textual description will always begin at next line )
  if(($token1 eq "CONTACT-INFO") && $flag) { $contflag = 1; }
  if(($contflag==1) && ($contcont==0) && ($token1=~ /^"/)) # CONTACT-INFO text started
  {
    $contcont = 1; $contflag = 0;
  }
  if(($contcont==1) && ($items[$#items]=~ /".*$/)) # CONTACT-INFO text finished
  {
    $contcont = 0; $contflag = 0;
  }





# search '::='  here in this line or in one of subsequent lines after definition
  if($flag)
  {
    for($i=1; ($i<=$#items); $i++)
    {
      if( ($items[$i] =~ /::=/) && ($items[$i+1] eq "{") &&  ($items[$i+4] eq "}") && (desccont==0) ) # true candidate
      {
          $pref = $items[$i+2];
          $suff = int($items[$i+3]);
          $known = grep(/^$pref/, keys %names);

          if ( ! $known )         # ask for unknown name
          {
            print "oid for ", $pref, " ?\n";
            $oidline = <STDIN>;
            $oidline =~ s/\n$//;

            $names{$pref} = $oidline;
            if(int($suff) == 0) { $names{$name} = $names{$pref}.".0"; }
	    else { $names{$name} = $names{$pref}.".".$suff; }
	    print "learned ",$name," as ",$names{$name},"\n";

            $hash{$name} = $names{$name};

            $nested{$pref} = 0;
            $nested{$name} = 1;
          }
          else                    # find oid by known name
          {
            while((($key,$val) = each %names))
            {
                if( $key eq $pref )
                {
		  if(int($suff) == 0) { $names{$name} = $val.".0"; }
	          else { $names{$name} = $val.".".$suff; }
                  $hash{$name} = $names{$name};
                  $nested{$name} = 1 + $nested{$key};
                  if($key =~ /Entry$/) { $column{$name} = 1; }
                }
            }
          }
          $flag = 0;              # oid found
      }
    }
  }
}

@oids_sorted = sort oidcmp values %hash;

print "======================\n";

print "hash sorted by oids\n";
for( $k=0; $k<=$#oids_sorted; $k++ )
{
  while(($key,$val) = each %hash)
  {
    if( $hash{$key} eq $oids_sorted[$k] )
    {
       $table[$k][0] = $key;                    # node name
       $table[$k][1] = $val;                    # node oid
       $table[$k][2] = $types{$key};            # node type in hierarchy abbreviated to one char
       $table[$k][3] = $nested{$key};           # node nesting level
       $table[$k][5] = 0;                       # node has_child in tree.html
       $table[$k][6] = 0;                       # mode has_sibling in tree.html
       $table[$k][8] = $syntax{$key};           # node syntax
       $table[$k][9] = $desc{$key};             # node description
       $table[$k][9] =~ s/"//g;
       $table[$k][10] = $short_syntax{$key};    # node short syntax for static .html
       $table[$k][11] = $access{$key};          # node max-access
       $table[$k][12] = $objgrp{$key};          # objects group definition under OBJECTS-GROUP node
       $table[$k][12] =~ s/\{//g;
       $table[$k][12] =~ s/\}//g;
       $table[$k][13] = $ntfgrp{$key};          # notifications group definition under NOTIFICATION-GROUP node
       $table[$k][13] =~ s/\{//g;
       $table[$k][13] =~ s/\}//g;
       $table[$k][14] = $ntf{$key};             # notification objects definition under NOTIFICATION-TYPE node
       $table[$k][14] =~ s/\{//g;
       $table[$k][14] =~ s/\}//g;

       printf ("%03d",$k);
       print " ";

       if   ($types{$key} eq "MODULE-IDENTITY") { $table[$k][4] = "M"; print "M"; }
       elsif($types{$key} eq "OBJECT_IDENTIFIER") { $table[$k][4] = "N"; print "N"; }
       elsif($types{$key} eq "OBJECT-TYPE")
       {
         if ( $column{$key} ) { $table[$k][4] = "C"; print "C"; }
         elsif ( $key =~ /Entry$/ ) { $table[$k][4] = "E"; print "E"; }
         elsif ( $key =~ /Table$/ ) { $table[$k][4] = "T"; print "T"; }
         else {  $table[$k][4] = "O"; print "O"; }
       }
       elsif($types{$key} eq "NOTIFICATION-TYPE") { $table[$k][4] = "t"; print "t"; }
       elsif($types{$key} eq "MODULE-COMPLIANCE") { $table[$k][4] = "m"; print "m"; }
       elsif($types{$key} eq "OBJECT-GROUP") { $table[$k][4] = "o"; print "o"; }
       elsif($types{$key} eq "NOTIFICATION-GROUP") { $table[$k][4] = "n"; print "n"; }
       else { $table[$k][4] = "?"; print "?"; }

       for($t=0; $t<=$nested{$key}; $t++) { print " "; }

       printf ("%-30s",$key);
       for($t=0; $t<=10-$nested{$key}; $t++) { print " "; }

       print $table[$k][1]," \n";

    }
  }
}

# ----------------------------------------------------------------------------------.tree.html

for( $k=0; $k<=$#oids_sorted; $k++ )
{
  if($table[$k][3] < $table[$k+1][3]) { $table[$k][5] = 1; } # has child
  for( $n= $k+1; $n<=$#oids_sorted; $n++ )
  {
    if($table[$k][3] == $table[$n][3])                       # sibling candidates have equal nested values (hence. same oid lengths)
    {
      $oid1line = $table[$k][1];
      $oid2line = $table[$n][1];
      if( sibling )                                          # has sibling
      {
        { $table[$k][6] = 1; }
      }
    }
  }

  # appending images by type
  if($table[$k][4] eq "M")                          # modident.gif for MODULE-IDENTITY
    { $table[$k][7] = "modident.gif"; }
  elsif($table[$k][4] eq "N")                       # object.gif for OBJECT IDENTIFIER (intermediate)
    { $table[$k][7] = "object.gif"; }
  elsif($table[$k][4] eq "O")                       # scalar.gif for OBJECT-TYPE scalar
    { $table[$k][7] = "scalar.gif"; }
  elsif($table[$k][4] eq "T")                       # table.gif for Table
    { $table[$k][7] = "cell_table.gif"; }
  elsif($table[$k][4] eq "E")                       # entry.gif for TableEntry
    { $table[$k][7] = "tab_entry.gif"; }
  elsif($table[$k][4] eq "C")                       # column.gif for column
    { $table[$k][7] = "columnar.gif"; }
  elsif($table[$k][4] eq "t")                       # trap.gif for NOTIFICATION-TYPE
    { $table[$k][7] = "trap.gif"; }
  elsif($table[$k][4] eq "m")                       # modcomp.gif for MODULE-COMPLIANCE
    { $table[$k][7] = "modcomp.gif"; }
  elsif($table[$k][4] eq "o")                       # objgroup.gif for OBJECT-GROUP
    { $table[$k][7] = "objgroup.gif"; }
  elsif($table[$k][4] eq "n")                       # notifgroup.gif for NOTIFICATION-GROUP
    { $table[$k][7] = "notifgroup.gif"; }
  else                                              # object.gif for the rest unknown
    { $table[$k][7] = "object.gif"; }
}

$window_title = $ARGV[1].".tree.html";
$filename = $window_title;
open(my $fh, '>', $filename) or die $!;

# head
print $fh "<html>\n<head>\n";
print $fh "\t<meta http-equiv=\"content-type\" content=\"text/html;charset=iso-8859-1\">\n";

print $fh "<style type=\"text/css\">\n";
print $fh "body	{margin-left: 3px; margin-right: 3px; margin-top: 3px; margin-bottom: 3px; font: 10pt Tahoma, Verdana, Geneva, Arial, Helvetica, sans-serif; color: #000000; background-color: #FFFFFF;}\n";
print $fh "table	{font: 10pt Tahoma, Verdana, Geneva, Arial, Helvetica, sans-serif; color: #000000; background-color: #FFFFFF;}\n";
print $fh ".mibtitle	{font: 14pt Tahoma, Verdana, Geneva, Arial, Helvetica, sans-serif; color: #ed2596; background-color: #FFFFFF; FONT-WEIGHT: bold; }\n";
print $fh ".trigger	{cursor: pointer}\n";
print $fh ".branch 	{display: none; margin-left: 0px;}\n";
print $fh ".blank	{cursor: default;}\n";
print $fh "a:link    {color:#000000; background-color:transparent; text-decoration: none;}\n";
print $fh "a:visited {color:#000000; background-color:transparent; text-decoration: none;}\n";
print $fh "a:active  {color:#000000; background-color:transparent; text-decoration: none;}\n";
print $fh "a:hover   {color:#000000; background-color:transparent; text-decoration: underline;}\n";
print $fh "</style>\n";

printf $fh "<title>MIB: %s tree</title>\n", $tab_title;
print $fh "</head>\n<body>\n";

# body
print $fh "<img name=\"expand\" title=\"Expand whole tree\" src=\"img/expand_up_cut.gif\" border=\"0\" onClick=\"expandAll()\" onmouseup=\"pressButton ('expand','img/expand_up_cut.gif')\" onmousedown=\"pressButton('expand','img/expand_down_cut.gif')\">\n";
print $fh "<img name=\"collapse\" title=\"Collapse whole tree\" src=\"img/collapse_up_cut.gif\" border=\"0\" onClick=\"collapseAll()\" onmouseup=\"pressButton ('collapse','img/collapse_up_cut.gif')\" onmousedown=\"pressButton('collapse','img/collapse_down_cut.gif')\"><br><br>\n";
printf $fh "<span class=\"mibtitle\"> %s </span>\n", $tab_title;
print $fh "<hr width=\"1000%\" size=1 color=\"black\">\n";

print $fh "<script language=\"JavaScript\" src=\"my_mibtree-9",$ARGV[2],".js\"></script>\n"; # now with syntax and max-access columns and with description and syntax in neighbor frame
print $fh "<script language=\"JavaScript\">\n";
print $fh "var tree_items = new Array();\n";

for($k = 0; $k<=$#oids_sorted; $k++ )
{
  # if there is not-empty DESCRIPTION or OBJECT-GROUP or NOTIFICATION-GROUP or NOTIFICATION-TYPE clause
  if(($table[$k][9] ne "")||($table[$k][12] ne "")||($table[$k][13] ne "")||($table[$k][14] ne ""))
    { $link = $ARGV[1].".defs.html#".$table[$k][0]; }
  else { $link = ""; }
  # tree_items[n] = new tree_node('name', 'link', 'icon', 'unused', 'oid', 'max-access', 'syntax', 'depth', 'has_child', 'has_sibling');
  print $fh "tree_items[",$k,"] = new tree_node('",$table[$k][0],"', '",$link,"', '",$table[$k][7],"', '', '",$table[$k][1],"', '",$table[$k][11],"', '",$table[$k][10],"', ",$table[$k][3],", ",int($table[$k][5]),", ",int($table[$k][6]),");\n";
}

print $fh "create_table();\n";
print $fh "</script>\n";

# bottom
print $fh "</body>\n</html>\n";
close $fh;
#print "created ", $filename, "\n";

# ----------------------------------------------------------------------------------.defs.html
$window_title = $ARGV[1].".defs.html";
$filename = $window_title;
open(my $fh, '>', $filename) or die $!;

# head
print $fh "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
print $fh "<html>\n<head>\n";
print $fh "\t<meta http-equiv=\"content-type\" content=\"text/html;charset=iso-8859-1\">\n";
print $fh "<style type=\"text/css\">\n";
print $fh "body	{margin-left: 3px; margin-right: 3px; margin-top: 3px; margin-bottom: 3px; font: 10pt Tahoma, Verdana, Geneva, Arial, Helvetica, sans-serif; color: #000000; background-color: #FFFFFF;}\n";
print $fh ".SMIname { COLOR: #2351dc; FONT-WEIGHT: bold; }\n";
print $fh ".SMIsyntax { COLOR: #cc0000; FONT-WEIGHT: bold; }\n";
print $fh ".SMIobjgrp { COLOR: #f18210; FONT-WEIGHT: bold; }\n";
print $fh ".SMIntfgrp { COLOR: #16b432; FONT-WEIGHT: bold; }\n";
print $fh ".SMIntfobj { COLOR: #16b432; FONT-WEIGHT: bold; }\n";
print $fh "</style>\n";

printf $fh "<title>%s</title>\n", $tab_title;
print $fh "</head>\n<body>\n";

#body
for($k = 0; $k<=$#oids_sorted; $k++ )
{
  if(($table[$k][9] ne "")||($table[$k][12] ne "")||($table[$k][13] ne "")||($table[$k][14] ne ""))
  {
    print $fh "<div id=\"",$table[$k][0],"\">\n";
    print $fh "<span class=\"SMIname\">",$table[$k][0],"</span>\n";
    print $fh "<p>",$table[$k][9],"</p>\n";
    if($table[$k][8])  { print $fh "<p><span class=\"SMIsyntax\">Syntax: </span>",$table[$k][8],"</p>\n"; }
    if($table[$k][12]) { print $fh "<p><span class=\"SMIobjgrp\">Objects: </span></p><p>",$table[$k][12],"</p>\n"; }
    if($table[$k][13]) { print $fh "<p><span class=\"SMIntfgrp\">Notifications: </span></p><p>",$table[$k][13],"</p>\n"; }
    if($table[$k][14]) { print $fh "<p><span class=\"SMIntfobj\">Notification objects: </span></p><p>",$table[$k][14],"</p>\n"; }
    print $fh "<hr width=\"90%\" size=1 color=\"green\">\n";
    print $fh "</div>\n";
  }
}
print $fh "</body>\n</html>\n";
close $fh;
#print "created ", $filename, "\n";

# ---------------------------------------------------------------------------------.frame.html
$window_title = $ARGV[1].".frame.html";
$filename = $window_title;
open(my $fh, '>', $filename) or die $!;

# head
print $fh "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
print $fh "<html>\n";
printf $fh "<title>%s</title>\n", $tab_title;

print $fh "<frameset cols=\"82%, *\" border= \"3\" frameborder= \"1\">\n";
print $fh "<frame src=\"",$ARGV[1].".tree.html","\" name=\"mibtree\" scrolling= \"auto\">\n";
print $fh "<frame src=\"",$ARGV[1].".defs.html","\" name=\"mibdefs\" scrolling= \"auto\" frameborder= \"1\" marginwidth=\"10\">\n";
print $fh "<noframes>\n";
print $fh "<body>Your browser does not support frames!</body>\n";
print $fh "</noframes>\n";
print $fh "</frameset>\n";
print $fh "</html>\n";
close $fh;
#print "created ", $filename, "\n";


print "====== THE END =======\n";
