package com.skr.mdm.util;

import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 获取Linux服务器的基本信息
 */
public class LinuxServerUtil {

    /**
     * 获取 CPU 序列号
     * @return
     */
    public static String getCPUSerial() {
        String serialNumber = null;
        try {
            //序列号
            serialNumber = "";
            //使用 dmidecode 命令获取 CPU 序列号
            String[] shell = {"/bin/bash", "-c", "dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1"};
            Process process = Runtime.getRuntime().exec(shell);
            process.getOutputStream().close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line = reader.readLine().trim();
            if (StringUtils.hasText(line)) {
                serialNumber = line;
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return serialNumber;
    }

    /**
     * 获取主板序列号
     * @return
     * @throws Exception
     */
    public static String getMainBoardSerial() {
        String serialNumber = null;
        try {
            //序列号
            serialNumber = "";
            //使用 dmidecode 命令获取主板序列号
            String[] shell = {"/bin/bash", "-c", "dmidecode | grep 'Serial Number' | awk -F ':' '{print $2}' | head -n 1"};
            Process process = Runtime.getRuntime().exec(shell);
            process.getOutputStream().close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = reader.readLine().trim();
            if (StringUtils.hasText(line)) {
                serialNumber = line;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return serialNumber;
    }
}
