#!/usr/bin/perl

BEGIN {

    require '/usr/sec/lib/SecBinLog.pm';
    SecBinLog::sb_log(); # Writes an entry to /var/log/legacy/sec-bin.log
}

#
# $Id: setipmi,v 1.3 2014/01/21 01:22:24 robert Exp $
#
use strict;
use JSON qw(encode_json decode_json to_json from_json);
use Data::Dumper;
use File::Slurp;
use LWP::UserAgent;

if(grep(/background/, @ARGV)){
  require Proc::Daemon;
  Proc::Daemon::Init();
}

my $ipmicfg = "/usr/sbin/ipmicfg";

my $go = 1;

#assume we are a production box
my $url = "https://mgmt.unifiedlayer.com/cgi-bin/ipmi_info";


#ipmimac
my $ipmimac = "";
my $ipmicfgip = `$ipmicfg -m`;
if($ipmicfgip =~ m/MAC=(.*)/){
  $ipmimac = $1;
}


my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(POST => $url);
$req->content_type('application/x-www-form-urlencoded');
$req->content("mac=$ipmimac");
my $res = $ua->request($req);
my $response = $res->content;
#print "RESPONSE\n$response\nENDRESPONSE\n";

my $data = decode_json($response);

#print Dumper($data);

#check results
my $error = "";
foreach my $key (qw{ip_ipmi netmask gateway }){
  unless($data->{$key} and $data->{$key} =~ m/^\d+\.\d+\.\d+\.\d+$/ ){
    $error .= "no valid $key ".$data->{$key}."\n";
  }
}
unless($data->{vlan_number} and $data->{vlan_number} =~ m/^\d+$/){
  $error .= "no valid vlan_number ".$data->{vlan_number}."\n";
}
if($error ne ""){
  diewith("fatal error: $error\n");
}

#make the changes
attemptrun("ipmi dhcp disable", "$ipmicfg -dhcp off");
attemptrun("ipmi vlan", "$ipmicfg -vlan on ".$data->{vlan_number} );
attemptrun("ipmi ip", "$ipmicfg -m ".$data->{ip_ipmi} );
attemptrun("ipmi ip nm", "$ipmicfg -k ".$data->{netmask} );
attemptrun("ipmi ip gw", "$ipmicfg -g ".$data->{gateway} );


sub attemptrun {
  print $_[0]."\n";
  if(runcmd($_[1])){
    diewith("failed on: ".$_[0]);
  }
}
sub diewith {
  my $msg = shift;
  print "fatal error encountered: $msg\n";
  $msg =~ s/'/ /g;
  exit 3;
}
sub runcmd {
  my $cmd = join(" ",@_);
  print "  $cmd\n";
  return system(@_) if $go;
  return 0;
}




