package utils

import (
	"github.com/shirou/gopsutil/v4/cpu"
	"github.com/shirou/gopsutil/v4/load"
	"github.com/shirou/gopsutil/v4/mem"
	"os"
	"strconv"
	"time"
)

/*
	获取系统相关信息
*/

type SysInfo struct {
	Hostname         string    // 主机名
	CPUPercent       float64   // CPU使用率
	LoadAverage1     float64   // 1分钟内平均负载
	LoadAverage5     float64   // 5分钟平均负载
	LoadAverage15    float64   // 15分钟平均负载
	MemTotal         uint64    // 总内存
	SwapTotal        uint64    // 总swap
	MemUsage         uint64    // 已使用内存
	SwapUsage        uint64    // 已使用swap
	MemUsagePercent  float64   // 已使用内存百分比
	SwapUsagePercent float64   // 已使用swap百分比
	DateTime         time.Time // 系统时间
	SysUser          string    // 当前用户
}

func GetSysInfo() (*SysInfo, error) {
	hn, err := os.Hostname()
	if err != nil {
		return nil, err
	}
	result := SysInfo{}
	result.Hostname = hn
	l, err := load.Avg()
	if err != nil {
		return nil, err
	}
	c, err := cpu.Percent(0, false)
	if err != nil {
		return nil, err
	}
	result.CPUPercent = c[0]
	result.LoadAverage1 = l.Load1
	result.LoadAverage5 = l.Load5
	result.LoadAverage15 = l.Load15
	sm, err := mem.SwapMemory()
	if err != nil {
		return nil, err
	}
	result.SwapTotal = sm.Total
	result.SwapUsage = sm.Used
	result.SwapUsagePercent = sm.UsedPercent
	vm, err := mem.VirtualMemory()
	if err != nil {
		return nil, err
	}
	result.MemTotal = vm.Total
	result.MemUsage = vm.Used
	result.MemUsagePercent = vm.UsedPercent
	result.DateTime = time.Now()
	sysu, err := GetSysUserById(os.Getuid())
	if err != nil || sysu == nil {
		result.SysUser = strconv.Itoa(os.Getuid())
	} else {
		result.SysUser = sysu.Name
	}
	return &result, nil
}
