#!/usr/bin/perl
#
# SNMPTTCONVERTMIB v1.3
#
# Copyright 2002-2007 Alex Burger
# alex_b@users.sourceforge.net
#
# 8/14/2002
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
##############################################################################
#
# http://www.sourceforge.net/projects/snmptt
#
###############################################################################
use strict;

#
# OPTIONS START
#
# Set this to '' to have no default EXEC line added, or modify as needed.
# Can also set on the command line with --exec='string'
my $defaultexec = '';

# Choose what type of quotes (if any) you want around the SUMMARY text pulled from the MIB.
#$defaultexecquote = '';		# no quotes
#$defaultexecquote = "\'";		# single (') quotes
my $defaultexecquote = "\"";		# double (") quotes

# Set this to 1 to have the --TYPE string prepended to the --SUMMARY string.
# Set to 0 to disable
my $prepend_type = 1;

#
# OPTIONS END
#
#############################################################################
#

my $snmpttconvertmib_version = "v1.3";

sub showversion
{
  print "\nSNMPTTCONVERTMIB $snmpttconvertmib_version\n";
  print "(c) 2002-2007 Alex Burger\n";
  print "http://snmptt.sourceforge.net\n\n";
}

##############################################################################
# Process command line arguments

$| = 1;

use Getopt::Long;
use File::Basename;
use File::Spec;

my $DEBUGGING = 0;

my $version = 0;
my $debug = 0;
my $help = 0;
my $net_snmp_perl = 0;
my $in = '';
my $out = '';
my $nodes = '';
my $no_description = 0;
my $no_variables = 0;
my $no_format_summary = 0;
my $no_format_desc = 0;
my $format = 0;
my $format_desc = 0;
my $no_desc_wildcard = 0;
my $no_severity = 0;
my $severity = 'Normal';
my $exec = '';


GetOptions 	('version' => \$version,
		'debug:i' => \$debug,
		'help' => \$help,
		'in=s' => \$in,
		'out=s' => \$out,
		'net_snmp_perl' => \$net_snmp_perl,
		'nodes=s' => \$nodes,
		'no_description' => \$no_description,
		'no_variables' => \$no_variables,
		'no_format_summary' => \$no_format_summary,
		'no_format_desc' => \$no_format_desc,
		'no_severity' => \$no_severity,
		'severity=s' => \$severity,
		'format=n' => \$format,
		'format_desc=n' => \$format_desc,
		'no_desc_wildcard' => \$no_desc_wildcard,
		'exec=s' => \$exec);

if ($version == 1)
{
  &showversion;
  exit(0);
}

if ($help == 1)
{
  &show_help();
  exit(0);
}

# Replace any spaces with -'s in severity
$severity =~ s/ /-/g;

if ($debug == 1)
{
  $DEBUGGING = 1;
}
if ($debug == 2)
{
  $DEBUGGING = 2;
}

if (($in eq "") || ($out eq ""))
{
  print "\nMissing arguments!\n";
  &show_help();
  exit 1;
}

# Get complete path of input file (MIB) in a portable way (needed for -m switch for snmptranslate)
my $dirname = dirname $in;
my $basename = basename $in;
my $input = File::Spec->catfile($dirname, $basename);

# Get complete path of output file (.conf) in a portable way 
$dirname = dirname $out;
$basename = basename $out;
my $output = File::Spec->catfile($dirname, $basename);

if ($exec ne '')
{
  $defaultexec = $exec;
  print "exec: $exec\n";
}

#print "nodes: $nodes\n";

if ($net_snmp_perl == 1)
{  
  print "\n\n*****  UCD-SNMP / NET-SNMP Perl module enabled *****\n\n";
}

print "\n\n*****  Processing MIB file *****\n\n";
my $snmptranslate_use_On;
check_snmptranslate_version();


print "severity: $severity\n";
print "\nFile to load is:        $input\n";
print "File to APPEND TO:      $output\n";

# Set MIBS environment variable to the filename of the MIB file (not the mib name - if a file contains
# multiple MIB definitions in one file, the mib name will not work - at least with 5.0.8 and older)
$ENV{MIBS} = $input;
print "\nMIBS environment var:   $ENV{MIBS}\n";

if ($DEBUGGING >= 1)
{
  print "\nLoading$input\n";
}

unless (open INPUTFILE, "<$input")
{
  die "Cannot open input file: $!";
}

my @mibfile;

while (<INPUTFILE>)
{
  chomp;			# remove <cr> at end of line
  s/\015//;			# Remove any DOS carriage returns
  push(@mibfile, $_);		# add to each line to @trapconf array
}

if ($DEBUGGING >= 1)
{
  print "Finished loading $input\n\n";
}

my $currentline=0;

unless (open OUTPUTFILE, ">>$output")
{
  die "Cannot open output file: $!";
}

# A mib file can contain multiple BEGIN definitions.  This finds the first one
# to make sure we have at least one definition.
# Determine name of MIB file
my $mib_name = '';
while ($currentline <= $#mibfile)
{
  my $line = $mibfile[$currentline];

  # Sometimes DEFINITIONS ::= BEGIN will appear on the line following the mib name.
  # Look for DEFINITIONS ::= BEGIN with nothing (white space allowed) around it and a previous line with 
  # only a single word with whitespace around it.
  if ($currentline > 0 && $line =~ /^\s*DEFINITIONS\s*::=\s*BEGIN\s*$/ && $mibfile[$currentline-1] =~ /^\s*(\S+)\s*$/) {
    # We should have found the mib name
    $mib_name = $1;
    print "\nSplit line DEFINITIONS ::= BEGIN found ($1).\n";
    $mib_name =~ s/\s+//g;
    last;
  }

  elsif ($line =~ /(.*)DEFINITIONS\s*::=\s*BEGIN/)
  {
    $mib_name = $1;
    $mib_name =~ s/\s+//g;
    last;
  }
  $currentline++;
}
print "mib name: $mib_name\n";
if ($mib_name eq '')
{
  print "\n\nAborting!!!\n";
  print "Could not find DEFINITIONS ::= BEGIN statement in MIB file!\n\n";
  exit (1);
}

if ($net_snmp_perl == 1)
{
  require SNMP;
  $SNMP::save_descriptions = 1;	# Need them only for looking up variable descriptions. 
                                # Do TRAP definition by hand to be able to pull out 
				# the SUMMARY lines
  &SNMP::initMib();
  
  print "\n\n*****  Using UCD-SNMP / NET-SNMP Perl module *****\n\n";
}

my $total_translations = 0;
my $successful_translations = 0;
my $failed_translations = 0;
$currentline=0;

#if ($net_snmp_perl == 0)
if (1)
{
  # Process the trap files by hand
  
  while ($currentline <= $#mibfile)
  {
    my $line = $mibfile[$currentline];

    # Sometimes DEFINITIONS ::= BEGIN will appear on the line following the mib name.
    # Look for DEFINITIONS ::= BEGIN with nothing (white space allowed) around it and a previous line with 
    # only a single word with whitespace around it.
    if ($currentline > 0 && $line =~ /^\s*DEFINITIONS\s*::=\s*BEGIN\s*$/ && $mibfile[$currentline-1] =~ /^\s*(\S+)\s*$/) {
      # We should have found the mib name
      print "\n\nSplit line DEFINITIONS ::= BEGIN found ($1).\n";

      $mib_name = $1;
      $mib_name =~ s/\s+//g;
      print "Processing MIB:         $mib_name\n";
     
      print OUTPUTFILE "#\n#\n#\n#\n";
      print OUTPUTFILE "MIB: $mib_name (file:$input) converted on " . scalar(localtime) . " using snmpttconvertmib $snmpttconvertmib_version\n";
      
      $currentline++; # Increment to the next line
      next;
    }

    elsif ($line =~ /(.*)DEFINITIONS\s*::=\s*BEGIN/)
    {
      $mib_name = $1;
      $mib_name =~ s/\s+//g;
      print "\n\nProcessing MIB:         $mib_name\n";
     
      print OUTPUTFILE "#\n#\n#\n#\n";
      print OUTPUTFILE "MIB: $mib_name (file:$input) converted on " . scalar(localtime) . " using snmpttconvertmib $snmpttconvertmib_version\n";
      
      $currentline++; # Increment to the next line
      next;
    }

    # TRAP-TYPE (V1) / NOTIFICATION-TYPE (V2)
    #
    # eg: 'mngmtAgentTrap-23003 TRAP-TYPE';
    # eg: 'ciscoSystemClockChanged NOTIFICATION-TYPE';
    if ( $line =~ /(.*)\s*TRAP-TYPE.*/ || 
         $line =~ /(.*)\s*(?<!--)NOTIFICATION-TYPE.*/ )
    {     
      my $trapname = $1;

      my $trapversion;
      if ( $line =~ /TRAP-TYPE/ )
      {
        $trapversion = 'TRAP';
      }
      else
      {
        $trapversion = 'NOTIFICATION';
      }
      
      # Make sure it doesn't start with a --.  If it does, it's a comment line..  Skip it
      if ($line =~/.*--.*TRAP-TYPE/ || $line =~/.*--.*NOTIFICATION-TYPE/)
      {
	# Comment line

	$currentline++; # Increment to the next line
	$line = $mibfile[$currentline]; # Get next line
	next;
      }

      my $enterprisefound = 0;
      
      my @variables = ();

      print "#\n";

      # Sometimes the TRAP-TYPE / NOTIFICATION-TYPE will appear on the line following the trap name
      # Look for xxx-TYPE with nothing (white space allowed) around it and a previous line with only a single word
      # with whitespace around it.
      if ( ($currentline > 0 && $line =~ /^\s*TRAP-TYPE\s*$/ && $mibfile[$currentline-1] =~ /^\s*(\S+)\s*$/) ||
           ($currentline > 0 && $line =~ /^\s*NOTIFICATION-TYPE\s*$/ && $mibfile[$currentline-1] =~ /^\s*(\S+)\s*$/) ) {
        # We should have found the trap name
        $trapname = $1;
        print "Split line TRAP-TYPE / NOTIFICATION-TYPE found ($1).\n";
      }
      
      # If the TRAP-TYPE / NOTIFICATION-TYPE line starts with white space, it's probably a import line, so ignore
      elsif ( $line =~ /^\s+TRAP-TYPE.*/ ||
           $line =~ /^\s+NOTIFICATION-TYPE.*/  ||
           $line =~ /^.*,.*NOTIFICATION-TYPE.*/ )
      {
        print "skipping a TRAP-TYPE / NOTIFICATION-TYPE line - probably an import line.\n";
        $currentline++; # Increment to the next line
        $line = $mibfile[$currentline]; # Get next line
        next;
      }
      
      # Remove beginning and trailing white space
      $trapname =~ /\s*([A-Za-z0-9_-]+)\s*/;
      $trapname = $1;
      
      
      print "Line: $currentline\n";
      if ($trapversion eq 'TRAP')
      {
        print "TRAP-TYPE: $1\n";		# If trapsummary blank, use trapsummary line for FORMAT and EXEC
      }
      else
      {
        print "NOTIFICATION-TYPE: $1\n";	# If trapsummary blank, use trapsummary line for FORMAT and EXEC
      }
      
      $currentline++; # Increment to the next line
      my $line3 = $mibfile[$currentline];
      
      my $end_of_definition = 0;
      
      my $traptype = "";
      my $trapsummary = "";
      my @description = ();
      my $trap_severity = $severity;
      my $enterprise;
      my @arguments;
      my $formatexec;
      
      while ( ($currentline <= $#mibfile) && !($line3 =~ /\s+END\s+/) && !($line3 =~ /(.*)\s+TRAP-TYPE.*/ )
      && !($line3 =~ /(.*)\s+NOTIFICATION-TYPE.*/) && ($end_of_definition == 0) )
      {
        # Keep going through the file until the next TRAP-TYPE / NOTIFICATION-TYPE or the end of the mib file
        # is reached, or the end of the section (between BEGIN and END)
        
        # Look for DESCRIPTION and anything after (including newline with /s)
        # and capture that anything in $1
        
        # If line starts with ENTERPRISE, pull it out
        # Only applies to SNMPv1 TRAPs
        # (SNMPv2 NOTIFICATIONS have the enterprise in the ::= line)
	
	$traptype = "";
	$trapsummary = "";
	@description = ();
	$trap_severity = $severity;
	
        if ($line3 =~ /ENTERPRISE\s+(.*)/)
        {
          $enterprise = $1;
          $enterprisefound =1;
        }

        if ( ($line3 =~ /VARIABLES(.*)/s) || ($line3 =~ /OBJECTS(.*)/s) )
        {
	  # If there is more text after the word VARIABLES or OBJECTS, assume it's the start of
	  # the variable list
	  my $templine = "";
	  if ($1 ne "")
          {
            $templine = $templine . $1;
            $templine =~ s/--.*//; # Remove any trailing comments
	  }
	  
	  if ($templine =~ /\}/)	# Contains a }, so we're done
	  {
	    # DONE!
	  }
	  else
	  {
	    $currentline++; # Increment to the next line
	    my $line4 = $mibfile[$currentline];
            $line4 =~ s/--.*//; # Remove any trailing comments
	    my $keepdigging = 1;
	    while (($currentline <= $#mibfile) && ($keepdigging == 1))
	    {
              $templine = $templine . $line4;
	      if ($line4 =~ /\}/)	# Contains a }, so we're done
	      {
		$keepdigging = 0;
	      }
	      else
	      {
		$currentline++; # Increment to the next line
		$line4 = $mibfile[$currentline];
                $line4 =~ s/--.*//; # Remove any trailing comments
	      }
	    }
	  }
	  $templine =~ s/\s//g;	# Remove any white space
	  $templine =~ /\{(.*)\}/; # Remove brackets
	  @variables = split /\,/, $1;
	  print "Variables: @variables\n";
	}
	
        if ($line3 =~ /DESCRIPTION(.*)/s)
        {
          my $temp1 = 0;
         
          # Start of DESCRIPTION
          
          #print "SDESC\n";
          
          # If there is more text after the word DESCRIPTION, assume it's the start of
          # the description.
          if ($1 ne "")
          {
            # Pull out text and remove beginning and trailing white space
            if ($1 =~ /\s*(.*)\s*/)
            {
              # Remove any quotes
              $_ = $1;
              s(\")()g;
              # "
              push (@description, "$_\n");
              
            }
          }
          
          $currentline++; # Increment to the next line
          my $line4 = $mibfile[$currentline];
          
          # Assume the rest is the description up until a ::= or end of the file
          while (! ($line4 =~ /::=/))
          {
            # If next line is a --#TYPE, pull out the information and place in $traptype
            if ($line4 =~ /--#TYPE(.*)/)
            {
              
              # Pull out text and remove beginning and trailing white space and quotes
              if ($line4 =~ /\s*--#TYPE\s*(.*)\s*/)
              {
                # Remove any quotes
                $_ = $1;
                s(\")()g;
                # "
                
                #print ("2\n");
                $traptype = $_;
                #print "Type: $traptype \n";
              }
              
              # Increment to next line and continue with the loop
              $currentline++; # Increment to the next line
              $line4 = $mibfile[$currentline];
              next;
            }
            
            # If next line is a --#SUMMARY, pull out the information and place in $summary
            if ($line4 =~ /--#SUMMARY(.*)/)
            {
              
              # Pull out text and remove beginning and trailing white space and quotes
              if ($line4 =~ /\s*--#SUMMARY\s*(.*)\s*/)
              {
                # Remove any quotes
                $_ = $1;
                s(\")()g;
                # "
                
                #print ("2\n");
                $trapsummary .= $_;
                #print "Summary: $trapsummary \n";
              }
              
              # Increment to next line and continue with the loop
              $currentline++; # Increment to the next line
              $line4 = $mibfile[$currentline];
              next;
            }
            # If next line is a --#ARGUMENTS, pull out the information and place in $arguments
            if ($line4 =~ /--#ARGUMENTS\s*{(.*)}/)
            {
              @arguments = split /,/, $1;

              for(my $i=0;$i <= $#arguments;$i++)
              {
                # Most ARGUMENTS lines have %n where n is a number starting 
                # at 0, but some MIBS have an ARGUMENTS line that have $1, $2,
                # etc and start at 1.  These need to have the $ removed and 
                # the number downshifted so the FORMAT will be generated 
                # properly.
                if ($arguments[$i] =~ /^\s*\$\d+/) {
                  $arguments[$i] =~ s/^\s*\$(\d+)/$1/;
                  $arguments[$i]--;
                }
                #print "argument $i: $arguments[$i]\n";
              }

              
              #for(my $i=0;$i <= $#arguments;$i++)
              #{
                #print "argument $i: $arguments[$i]\n";
              #}
              
              # Increment to next line and continue with the loop
              $currentline++; # Increment to the next line
              $line4 = $mibfile[$currentline];
              next;
            }
	    # If next line is a --#SEVERITY, pull out the information and place in $trap_severity
            if ($line4 =~ /--#SEVERITY\s+(.*)/ && ! ($line4 =~ /--#SEVERITYMAP/))
            {
              # Pull out text and remove beginning and trailing white space and quotes
              if ($line4 =~ /\s*--#SEVERITY\s+(.*)\s*/)
              {
                # Remove any quotes
                $_ = $1;
                s(\")()g;
                # "
                
                #print ("2\n");
                if ($no_severity == 0)
		{
		  $trap_severity = $_;
		}
                #print "Severity: $trap_severity \n";
              }
              # Increment to next line and continue with the loop
              $currentline++; # Increment to the next line
              $line4 = $mibfile[$currentline];
              next;
            }
            # If next line starts with a --#, ignore it and continue with the loop
            # (we already got the SUMMARY line above)
            if ($line4 =~ /--#/)
            {
              $currentline++; # Increment to the next line
              $line4 = $mibfile[$currentline];
              next;
            }
            
            # If we did not find text after the word DESCRIPTION, then the NEXT
            # line must be the first line of description.
            
            # Remove beginning and trailing white space
            $line4 =~ (/\s*(.*)\s*/);
            if ($1 ne "")
            {
              # Remove any quotes
              $_ = $1;
              s(\")()g;
              # "
              
              push (@description, "$_\n");
              #print "c:$_\n";
            }
            
            $currentline++; # Increment to the next line
            $line4 = $mibfile[$currentline];
          }
          #print "EDESC\n";
          
          if ($line4 =~ /::=/)
          {
            $end_of_definition = 1;		# Move on to the next one
            
            if ($enterprisefound == 0)
            {
              # $line4 should now contain ::= line
              # # Pull out enterprise from { }
              # # Would only apply to SNMPv2 NOTIFICATIONS
              # #print "Line4: $line4\n";
              $line4 =~ /{(.*)\s\d.*/;
              
              #print "\$1=$1\n";
              $enterprisefound =1;
              
              # Remove any spaces
              $_ = $1;
              s( )()g;
              $enterprise = $_;
              print "Enterprise: $enterprise\n";
            }
          }
        }
        $currentline++; # Increment to the next line
        $line3 = $mibfile[$currentline];
      }
      
      # Combine Trap type and summary together to make new summary
      if ($traptype ne "" && $prepend_type == 1)
      {
        $trapsummary = $traptype . ": " . $trapsummary;
      }
      
      my $trap_lookup;
      if ($mib_name eq '')
      {
	$trap_lookup = $trapname;
      }
      else
      {
	$trap_lookup = "$mib_name\:\:$trapname";
      }
      print "Looking up via snmptranslate: $trap_lookup\n";
      
      my $trapoid;
      if ($snmptranslate_use_On == 1)
      {
	$trapoid = `snmptranslate -IR -Ts -On $trap_lookup`;
      }
      else
      {
	$trapoid = `snmptranslate -IR -Ts $trap_lookup`;
      }
      
      chomp $trapoid;
      if ($trapoid ne "")
      {
        print OUTPUTFILE "#\n#\n#\n";
        print OUTPUTFILE "EVENT $trapname $trapoid \"Status Events\" $trap_severity\n";
        
        # Loop through trapsummary and replace the %s and %d etc with %1 to %n
        
        #$j = $#arguments; # j is last element number
        #print "j is $j\n";
        
        # Change the %s or %d etc into $1 etc (starts at $1)
        $_ = $trapsummary;
        for (my $j=0; $j<= $#arguments; $j++)
        {
          my $variable = ($arguments[$j])+1;
          s(%[a-zA-Z])(\$$variable);
        }
        
        #print "new summary: $_\n";
        
        $trapsummary = $_;
        
        my $descriptionline1 = '';
        
        # Build description line for FORMAT / EXEC
        if ($format_desc == 0)		# First line of description
        {
          $descriptionline1 = $description[0];
          chomp ($descriptionline1);
        }
        else				# n sentence(s) of description
        {
          # Build single line copy of description
          my $description_temp;
          foreach my $a (@description)
          {
            my $b = $a;
            chomp($b);
            $description_temp = $description_temp . $b . " ";
          }
          chop $description_temp;
          
          # Split up based on sentences
          my @description_temp2 = split /\./, $description_temp;
          
          # Remove white space around each sentence and add a trailing .
          for (my $i=0 ; $i <= $#description_temp2; $i++)
          {
            $description_temp2[$i] =~ /\s*(.*)\s*/;
            $description_temp2[$i] = $1 . ".";
          }
          
          # Build description line based on the number of sentences requested.
          for (my $i=1 ; $i <= $format_desc; $i++)
          {
            if ($description_temp2[$i-1] ne '') {
              $descriptionline1 = $descriptionline1 . $description_temp2[$i-1] . " " ;
            }
          }
          chop $descriptionline1;	# Remove last space
        }
        
        if ($descriptionline1 ne "")
        {
          if ($descriptionline1 =~ /%[a-zA-Z]/)
          {
            # Sometimes the variables are in the first line of the description
            # Change the %s or %d etc into $1 etc (starts at $1)
            # There is no list of variables, so just put them in order starting at 1 and
            # going up to 20
            $_ = $descriptionline1;
            for (my $j=1; $j<= 20; $j++)
            {
              s(%[a-zA-Z])(\$$j);
            }
            $descriptionline1 = $_;
            #$descriptionlinehadvariables = 1;
          }
          else
          {
            if ($no_desc_wildcard == 0)
            {
              $descriptionline1 = "$descriptionline1 \$*";
            }
          }
        }
        
        $formatexec = '';
        
        if ($format == 0)	# --#SUMMARY or description
        {
          if ($trapsummary ne '' && $no_format_summary == 0)
          {
            $formatexec = $trapsummary;
          }
          elsif ($descriptionline1 ne '' && $no_format_desc == 0)
          {
            $formatexec = $descriptionline1;
          }
        }
        elsif ($format == 1)	# description or --#SUMMARY
        {
          if ($descriptionline1 ne '' && $no_format_desc == 0)
          {
            $formatexec = $descriptionline1;
          }
          elsif ($trapsummary ne '' && $no_format_summary == 0)
          {
            $formatexec = $trapsummary;
          }
        }
        elsif ($format == 2)	# --#SUMMARY and description
        {
          if ($trapsummary ne '' && $no_format_summary == 0)
          {
            $formatexec = $trapsummary;
          }
          if ($descriptionline1 ne '' && $no_format_desc == 0)
          {
            if ($formatexec =~ /\.$/)	# If it already ends in a .
            {
              $formatexec = $formatexec . " " . $descriptionline1;
            }
            else
            {
              $formatexec = $formatexec . ". " . $descriptionline1;
            }
          }
        }
        elsif ($format == 3)	# description and --#SUMMARY
        {
          if ($descriptionline1 ne '' && $no_format_desc == 0)
          {
            $formatexec = $descriptionline1;
          }
          if ($trapsummary ne '' && $no_format_summary == 0)
          {
            $formatexec = $formatexec . " " . $trapsummary;
          }
        }
        
        if ($formatexec ne '')
        {
          print OUTPUTFILE "FORMAT $formatexec\n";
          if ($defaultexec ne '')
          {
            print OUTPUTFILE "EXEC $defaultexec $defaultexecquote$formatexec$defaultexecquote\n"
          }
        }
        else
        {
          print OUTPUTFILE "FORMAT \$*\n";
          if ($defaultexec ne '')
          {
            print OUTPUTFILE "EXEC $defaultexec $defaultexecquote\$*$defaultexecquote\n"
          }
          #print OUTPUTFILE "EXEC \$*\n";
        }
        
        if ($nodes ne '')
        {
          print OUTPUTFILE "NODES $nodes\n";
        }
        
        if ($no_description == 0)
        {
          print OUTPUTFILE "SDESC\n";
          #print OUTPUTFILE "$descriptionline1\n";
          for (my $i=0; $i <= $#description; $i++)
          {
            print OUTPUTFILE "$description[$i]";
          }
	  
	  # If net_snmp_perl is enabled, lookup each variable
	  if (@variables && $no_variables == 0 && $net_snmp_perl == 1)
	  {
	    print OUTPUTFILE "Variables:\n";
	    for (my $i=0; $i <= $#variables; $i++)
	    {
	      printf OUTPUTFILE "%3d: %s\n",$i+1,$variables[$i];
	      printf OUTPUTFILE "     Syntax=\"" . $SNMP::MIB{$variables[$i]}{type} . "\"\n";
	      if (uc $SNMP::MIB{$variables[$i]}{type} =~ /INTEGER/)
	      {
		my $b = $SNMP::MIB{$variables[$i]}{enums};
		my %hash = %$b;
		my $i = 1;
		
		# Create a new copy of the hash swapping the key and the value
		my %temphash = ();
		while ((my $key, my $value) = each %hash)
		{
		  $temphash{$value} = $key;
		}
		# Print out the entries in the hash
		foreach my $c (sort keys %temphash)
		{
		  print OUTPUTFILE "       " . $c . ": $temphash{$c}\n";
		}
	      }
	      if ($SNMP::MIB{$variables[$i]}{description})
	      {
		print OUTPUTFILE "     Descr=\"" . $SNMP::MIB{$variables[$i]}{description} . "\"\n";
	      }
	    }
	  }
	  
	  elsif (@variables ne "" && $no_variables == 0  && $net_snmp_perl == 0)
	  {
	    print OUTPUTFILE "Variables:\n";
	    for (my $i=0; $i <= $#variables; $i++)
	    {
	      print OUTPUTFILE "  " . ($i+1) . ": " . $variables[$i] . "\n";
	    }
	  }
          print OUTPUTFILE "EDESC\n";
        }
        
        $currentline--;
      }
      
      print "OID: $trapoid\n";

      $total_translations++;
      if ($trapoid eq '')
      {
	$failed_translations++;
      }
      else
      {
	$successful_translations++;
      }
      
      #print "\@description is ", $#description,"\n";
      #print "going to next trap / notification\n\n";
    }
    
    $currentline++; # Increment to the next line
  }
  
  
  sub check_snmptranslate_version
  {
    $snmptranslate_use_On = 1;
    
    if (open SNMPTRANSLATE, "snmptranslate -V 2>&1|")
    {
      my $snmptranslatever = <SNMPTRANSLATE>;
      close SNMPTRANSLATE;
      
      chomp ($snmptranslatever);
      
      print "snmptranslate version: " . $snmptranslatever. "\n";
      
      if ($snmptranslatever =~ /UCD/i || $snmptranslatever =~ /NET-SNMP version: 5.0.1/i)
      {
        $snmptranslate_use_On = 0;
        if ($DEBUGGING >= 1)
        {
          print "snmptranslate is either UCD-SNMP, or NET-SNMP v5.0.1, so do not use the -On switch.  Version found: $snmptranslatever\n";
        }
      }
    }
  }
  # End of process the trap files by hand

  print "\n\nDone\n\n";
  print "Total translations:        $total_translations\n";
  print "Successful translations:   $successful_translations\n";
  print "Failed translations:       $failed_translations\n";

  if ($total_translations == 0) {
    print "\nThe MIB file did not contain any TRAP-TYPE or NOTIFICATION-TYPE definitions,\n";
    print "so no translations occured.  Try another MIB file.\n\n";
  }
}


sub show_help
{
  my $USAGE = qq/Usage:
  snmpttconvertmib --in= --out= [<options>]
Options:
  --debug=n              Set debug level (1 or 2)
  --help                 Display this message
  --version              Display author and version information
  --net_snmp_perl        Enable NET-SNMP Perl integration (see below)
  --in=filename          Input file
  --out=filename         Output file
  --nodes=name or file   If specified, will insert a NODES line after FORMAT or 
  			 EXEC.  The host name(s) separated by spaces, or the 
			 name of the nodes file.  Use quotes for multiple
			 entries.  See NODES section in readme.html for examples
  --no_description	 Do not save the description
  --no_variables	 Do not save the variable list in the description
  --no_format_summary	 Do not use the --#SUMMARY lines for FORMAT \/ EXEC
  --no_format_desc	 Do not use the description line for FORMAT \/ EXEC
  --no_severity 	 Do not use the --#SEVERITY line for EVENT line.  Default
                         severity of "Normal" will be used, unless --severity= is 
			 set
  --severity=s  	 Severity level for EVENT line.  Only used if there is no
                         --#SEVERITY line, or --no_severity is set.  Must NOT 
			 contain any spaces.
			 Example: 
			   Critical
  --format=n		 FORMAT \/ EXEC order preference
			   0 = --#SUMMARY or description
			   1 = description or --#SUMMARY
			   2 = --#SUMMARY and description
			   3 = description and --#SUMMARY
  --format_desc=n	 How to convert the description line for FORMAT \/ EXEC
			   0 = First line of description
			   n = n sentence(s) of description
  --no_desc_wildcard	 To prevent \$* from being appended to the end of 
  			 description text when used on the FORMAT \/ EXEC 
			 lines.  A wildcard is only used if the description 
			 line contained no variable definitions (\%n).
  --exec=command         Command line to use for EXEC line.  Use SINGLE quotes
                         with Unix.  Example:
    			   'qpage -f TRAP notifygroup1'
			   
  Note:  The only benefit in using the --net_snmp_perl switch (which requires the
         Net-SNMP Perl module to be installed) is that the Variables: description section 
         will include:
           -variable syntax
           -variable description
           -variable enums

	   For example:
           2: globalStatus
              Syntax="INTEGER"
                2: ok
                4: failure
              Descr="Current status of the entire library system"
/;
  
  &showversion;
  print $USAGE . "\n";
}
