package amt;

use warnings;
use strict;

use lib '/srv/Intel-AMT/lib/';
use Intel::AMT::RemoteControl;
use Intel::AMT::NetworkAdministration;
use Intel::AMT::EventManager;
use Data::Dump qw/dump/;
use Regexp::Common qw/net/;

use html;
use ping;
use store;
use Carp qw/confess/;

sub ip {
	my ( $client_ip, $amt ) = @_;
	return unless $client_ip;
	$amt ||= client::conf( $client_ip => 'amt' );
	my ( $passwd, $ip ) = split(/\s+/, $amt);
	( $ip, $passwd ) = ( $passwd, $ip ) if $passwd =~ m/$RE{net}{IPv4}/;

	$ip ||= $client_ip;

	$ENV{AMT_PASSWORD} = $passwd;
	$ENV{AMT_HOST} = $ip;

	my $hostname = client::conf( $client_ip => 'hostname' ) || $client_ip;

	client::conf( $ip => 'hostname', default => "amt-$hostname" );

	return $ip;
}

sub power_state {
	my $state = eval { Intel::AMT::RemoteControl::SystemPowerState };
	store::audit('SystemPowerState', { ip => $ENV{AMT_HOST}, SystemPowerState => $state });
	return $state;
}

sub power_on {
	ip @_;
	my $state = power_state;
	defined $state && ( $state & 0x0f ) == 0;
}

sub network {
	ip @_;

	my $amt = eval { Intel::AMT::NetworkAdministration::network_settings };
	if ( $@ ) {
		warn "ERROR $@";
	} else {
		$amt->{ip} = $ENV{AMT_HOST};
		store::audit('log', $amt );
	}
	$amt;
}

sub log {
	ip @_;

	my $amt = eval { Intel::AMT::EventManager::ReadEventLogRecords };
	if ( $@ ) {
		warn "ERROR $@";
	} else {
		$amt->{ip} = $ENV{AMT_HOST};
		store::audit('log', $amt );
	}
	$amt;
}

sub RemoteControl {
	ip shift;
	my $command = shift;
	eval { Intel::AMT::RemoteControl::run( $command ) };
	store::audit( $command, { ip => $ENV{AMT_HOST}, error => $@ } );
	warn "ERROR $@" if $@;
}

1;
