#!/usr/bin/env perl

use strict;
use warnings;

our $home;

BEGIN {
  use FindBin;
  FindBin::again();

  $home = ($ENV{NETDISCO_HOME} || $ENV{HOME});

  # try to find a localenv if one isn't already in place.
  if (!exists $ENV{PERL_LOCAL_LIB_ROOT}) {
      use File::Spec;
      my $localenv = File::Spec->catfile($FindBin::RealBin, 'localenv');
      exec($localenv, $0, @ARGV) if -f $localenv;
      $localenv = File::Spec->catfile($home, 'perl5', 'bin', 'localenv');
      exec($localenv, $0, @ARGV) if -f $localenv;

      die "Sorry, can't find libs required for App::Netdisco.\n"
        if !exists $ENV{PERLBREW_PERL};
  }
}

BEGIN {
  use Path::Class;

  # stuff useful locations into @INC and $PATH
  unshift @INC,
    dir($FindBin::RealBin)->parent->subdir('lib')->stringify,
    dir($FindBin::RealBin, 'lib')->stringify;

  use Config;
  $ENV{PATH} = $FindBin::RealBin . $Config{path_sep} . $ENV{PATH};
}

use App::Netdisco;
use Dancer ':script';
use Dancer::Plugin::DBIC 'schema';

use HTTP::Tiny;

binmode STDOUT, ":utf8";

my %urls = (
  enterprises => 'https://raw.githubusercontent.com/netdisco/upstream-sources/master/ieee/SMI/enterprise-numbers.txt',
);

my %enterprise = ();

foreach my $file (sort keys %urls) {
    my $resp = HTTP::Tiny->new->get($urls{$file});
    my $content = $resp->{content};
    my @lines = split m/\n/, $content;
    my $seen_start = false;
    my $number = 0;

    foreach my $row (@lines) {
        next if !defined $row or not length $row;
        $seen_start = true if $row eq '1';
        next if not $seen_start;

        if ($row =~ m/^\d+$/) {
            $number = $row;
        }
        elsif ($row =~ m/^\s\s\S/) {
            $enterprise{ $number } = $row;
        }
        else {
            $number = 0;
            next;
        }
    }
}

# roll everything back if we're testing
my $txn_guard = $ENV{ND2_DB_ROLLBACK}
  ? schema('netdisco')->storage->txn_scope_guard : undef;

schema('netdisco')->txn_do(sub{
    schema('netdisco')->resultset('Enterprise')->delete;

    schema('netdisco')->resultset('Enterprise')->populate([
        map {{
            enterprise_number => $_,
            organization  => $enterprise{$_},
        }} sort {$a <=> $b} keys %enterprise
    ]);
});

exit 0;

__DATA__

Decimal
| Organization
| | Contact
| | | Email
| | | |
0
  Reserved
    Internet Assigned Numbers Authority
      iana&iana.org
1
  NxNetworks
    Michael Kellen
      OID.Admin&NxNetworks.com
2
  IBM (https://w3.ibm.com/standards )
    Glenn Daly
      gdaly&us.ibm.com


