#!/usr/bin/env perl
# setmaxtc - build and use net-snmp with 16k MAXTC
# I blame (& owe credit to) jeneric ;-).

use strict;
use warnings;

use charnames ':full';
binmode STDOUT, ':utf8';
$|++;

use File::Temp;
use File::Path ();
use Time::HiRes 'sleep';
use Term::ANSIColor qw(:constants);
use File::Spec::Functions qw(splitdir catfile);
use Text::ParseWords 'shellwords';
use IPC::Open3 'open3';
use POSIX qw(:sys_wait_h);

use FindBin;
use lib catfile($FindBin::Bin, 'lib');
use Helpers;

our $NOTAVERSION = '1.0';
my $home = "$ENV{MIBHOME}/EXTRAS/net-snmp.local";
my $localenv = "$home/bin/localenv";
my $cpanm = 'cpanm --quiet --notest';
my $success = "$home/.success_$NOTAVERSION";
my %envbak = (); # backup %ENV

if (not -e $success) {
  File::Path::remove_tree($home);
  mkdir $home;

  bld(
    qq{ curl -sL https://cpanmin.us/ | perl - --quiet --notest --local-lib '$home' }
    .q{ App::cpanminus App::local::lib::helper PkgConfig Test::CChecker }
    .q{ Alien::zlib::Static }, 'net-snmp dependencies(1)');

  # back up and update environment
  foreach my $key (shellwords(bld(qq{ '$localenv' zlib-env-perl KEYS },
                                  'env(1a)'))) {
    $envbak{$key} = $ENV{$key} if !exists $envbak{$key};
    $ENV{$key} = bld(qq{ '$localenv' zlib-env-perl $key }, 'env(1b)');
  }

  bld(qq{ '$localenv' $cpanm Alien::OpenSSL::Static },
    'net-snmp dependencies(2)');

  # back up and update environment
  foreach my $key (shellwords(bld(qq{ '$localenv' openssl-env-perl KEYS },
                                  'env(2a)'))) {
    $envbak{$key} = $ENV{$key} if !exists $envbak{$key};
    $ENV{$key} = bld(qq{ '$localenv' openssl-env-perl $key }, 'env(2b)');
  }

  bld(qq{ '$localenv' $cpanm --installdeps Alien::SNMP::MAXTC },
    'net-snmp dependencies(3)');

  # restore environment
  foreach my $key (keys %envbak) {
    delete $ENV{$key};
    $ENV{$key} = $envbak{$key} if $envbak{$key};
  }

  bld(qq{ '$localenv' $cpanm Alien::SNMP::MAXTC },
    'net-snmp');

  open(my $ok, '>', $success) or die $!;  close $ok;
}

print "\N{HEAVY CHECK MARK} Entering localenv...\n";
my $bindir = qx('$localenv' perl -MAlien::SNMP::MAXTC -e 'print Alien::SNMP::MAXTC->bin_dir');
exec(qq{'$localenv' $ENV{SHELL} -c 'export PATH="$bindir:\$PATH";\$SHELL'});

sub bld {
  my $target = shift || return;
  my $alias  = shift || return;
  my $out = File::Temp->new();
  my $err = File::Temp->new();
  my $in  = '';

  my $pid = open3($in, $out, $err, $target);
  while (! waitpid($pid, WNOHANG)) {
    status("Building $alias...");
    sleep 0.05;
  }
  my $child_exit_status = $? >> 8;
  seek($_, 0, 0) for ($out, $err);
  ($out, $err) = (<$out>, <$err>);

  blank();
  if ($child_exit_status) {
    print RED, "\N{HEAVY BALLOT X} ", CYAN,
      "Errors from $alias build:\n", RESET;
    print $out, "\n---\n" if $out;
    print $err, "\n---\n" if $err;
    exit 1;
  }

  return $out;
}
