package PVE::API2::Hardware::NET;

use strict;
use warnings;

use PVE::JSONSchema qw(get_standard_option);

use PVE::RESTHandler;
use PVE::SysFSTools;

use base qw(PVE::RESTHandler);


__PACKAGE__->register_method({
    name => 'net',
    path => '',
    method => 'GET',
    permissions => {
	check => ['perm', '/nodes/{node}', [ 'Sys.Audit' ]],
    },
    description => "Read node network device ",
    protected => 1,
    proxyto => 'node',
    parameters => {
	additionalProperties => 0,
	properties => {
	    node => get_standard_option('pve-node'),
	    type => {
		description => "get type",
		type => 'string',
		optional => 1,
	    }
	}
    },
    returns => {
	type => 'array',
	items => {
	    type => "object",
	    properties => {
		name => {
		    type => 'string',
		    description => "The network name.",
		},
		driver => {
		    type => 'string',
		    description => 'The network dirver.',
		},
		pciid => {
		    type => 'string',
		    description => 'The network pciid.',
		},
		speed => {
		    type => 'string',
		    description => 'The network speed.',
		},
		devname => {
		    type => 'string',
		    description => 'The network devname.',
		}
	    }
	}
    },
    code => sub {
		my ($param) = @_;

		my $ip_output = `ip link|grep -E "eth|eno|ens|wl|enp" `;
		my @lines = split /\n/, $ip_output;
		my $nic_count = 0;
		my $res = [];
		foreach my $line (@lines) {
			if ($line =~ /(\d+): (\S+):/) {
				# 增加网卡计数
				$nic_count++;
				my ($index, $name) = ($1, $2);
				# 获取PCI槽位号和驱动信息
				my $pci_info = `ethtool -i $name | grep bus-info`;
				if ($pci_info =~ /bus-info:\s*(\S+)/) {
					my $slot = $1;
					my $driver = `lspci -ks $slot |grep "Kernel driver in use" | awk '{print \$5}'`;
					my $speed = `ethtool $name | grep Speed|awk '{print \$2}'`;
					my $devname = `lspci -ks $slot |grep "Subsystem" | cut -d ":" -f2`;
					# 输出网卡信息
					push @$res , {
						name => $name,
						driver => $driver,
						pciid  => $slot,
						speed => $speed,
						devname => $devname
					}
				}
			}
		}
	return $res;
    }});
