package PVE::API2::Ipmi;

use strict;
use warnings;

use Digest::MD5;
use Digest::SHA;
use Filesys::Df;
use HTTP::Status qw(:constants);
use JSON;
use POSIX qw(LONG_MAX);
use Time::Local qw(timegm_nocheck);
use Socket;
use IO::Socket::SSL;

use PVE::API2Tools;
use PVE::APLInfo;
use PVE::AccessControl;
use PVE::Cluster qw(cfs_read_file);
use PVE::DataCenterConfig;
use PVE::Exception qw(raise raise_perm_exc raise_param_exc);
use PVE::INotify;
use PVE::JSONSchema qw(get_standard_option);
use PVE::NodeConfig;
use PVE::Tools qw(file_get_contents);

use base qw(PVE::RESTHandler);

use PVE::API2::Hardware;
use PVE::API2::NodeConfig;


__PACKAGE__->register_method ({
    name => 'index',
    path => '',
    method => 'GET',
    description => "Index of ipmi tool",
    permissions => {
	user => 'all',
    },
    parameters => {
	additionalProperties => 0,
	properties => {
	    node => get_standard_option('pve-node'),
	},
    },
    returns => {
	type => 'array',
	items => {
	    type => "object",
	    properties => { type => { type => 'string'} },
	},
	links => [ { rel => 'child', href => "{type}" } ],
    },
    code => sub {
	my ($param) = @_;

	my $res = [
	    { type => 'power' },
	];

	return $res;
    }
});


__PACKAGE__->register_method({
    name => 'power',
    path => 'power',
    method => 'POST',
    permissions => {
	check => ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
    },
    description => "Set Node Power Status by IPMI",
    protected => 1,
    proxyto => 'node',
    parameters => {
	additionalProperties => 0,
	properties => {
        node => get_standard_option('pve-node'),
	    status => {
		description => "set power status",
		type => 'string',
		enum => [qw(on off cycle soft reset)],
	    },
        username => {
		description => "ipmi username",
		type => 'string'
        },
        password => {
		description => "ipmi username password",
		type => 'string'
	    },
        ip => {
		description => "ipmi ip address",
		type => 'string'
	    },
	},
    },
    returns => {
	type => "string"
    },
    code => sub {
        my ($param) = @_;

        my $node = $param->{node};
	    my $local_node = PVE::INotify::nodename();

        my $cmd = ["/usr/bin/ipmitool"];
        push @$cmd, '-H', $param->{ip};
        push @$cmd, '-U', $param->{username};
        push @$cmd, '-P', $param->{password};
        push @$cmd, 'power', $param->{status};
        my $res = qx(@$cmd);

	    return $res;
    }});

1;