#!/usr/bin/env perl
# importmibs new_dir
# will look into new_dir for MIBs to add or replace in MIBHOME/...

use strict;
use warnings;

use charnames ':full';
binmode STDOUT, ':utf8';

use File::Spec::Functions qw(splitdir catfile);
use Term::ANSIColor qw(:constants);

if (!defined $ENV{MIBHOME}) {
  print "error: must define \$MIBHOME (where the MIB dirs live)\n";
  exit(1);
}

my $from = shift;
if (!defined $from or not -d $from) {
  print "usage: $0 new_dir (named same as old_dir and containing new MIBs)\n";
  exit(1);
}

my $vendor = (grep {m/\S/} splitdir($from))[-1];
my $to = catfile($ENV{MIBHOME}, $vendor);
if (! -d $to) {
  print "error: no directory in MIBHOME named $vendor\n";
  exit(1);
}

if (scalar grep {-f} glob(catfile($from, 'error', '*'))) {
  print "error: prepmibs found some errors you need to address.\n";
  exit(1);
}

foreach my $fromfile (grep {-f} glob(catfile($from, '*'))) {
  my $name = (splitdir($fromfile))[-1];
  my $tofile = catfile($to, $name);

  if (-e $tofile) {
    print YELLOW, "\N{RIGHTWARDS WHITE ARROW FROM WALL} ";
  }
  else {
    print YELLOW, "\N{BLACK SMALL STAR} ";
  }
  print GREEN, "$name\n", RESET;

  # copy, and change underscores to hyphens in descriptors/identifiers
  open(my $mibfrom, '<', $fromfile) or die $!;
  open(my $mibto,   '>', $tofile) or die $!;
  while (my $line = <$mibfrom>) {
    $line =~ s/_/-/g
      if $line =~ m/\w_\w+\s*\(\d+\)/;
    print $mibto $line;
  }
  close $mibfrom;
  close $mibto;
}

print "\N{HEAVY CHECK MARK} Imported MIBs.\n";
exit(0);
