package utils

import (
	"fmt"
	"log"
	"os"
	"regexp"
	"strconv"

	"github.com/shirou/gopsutil/v4/process"
)

var (
	RePidNS = regexp.MustCompile(`pid:\[([1-9][0-9]*)]$`) // 匹配pid命名空间的正则表达式 pid:[4026545939]
)

// GetPidNS 获取指定进程的Pid命名空间号
func GetPidNS(pid uint64) (uint64, error) {
	str, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", pid))
	if err != nil {
		return 0, err
	}
	if !RePidNS.MatchString(str) {
		return 0, fmt.Errorf("error matching pid")
	}
	strs := RePidNS.FindStringSubmatch(str)
	if len(strs) < 2 {
		return 0, fmt.Errorf("error matching pid")
	}
	return strconv.ParseUint(strs[1], 10, 64)
}

// GetProcessInfo 获取进程信息
func GetProcessInfo(pid int32) {
	p, err := process.NewProcess(pid)
	if err != nil {
		return
	}
	p.Times()
	cmdStr, err := p.Cmdline()
	if err != nil {
		return
	}
	log.Println(cmdStr)
}

func GetProcessByName(cmdline string) ([]*process.Process, error) {
	p, err := process.Processes()
	if err != nil {
		return nil, err
	}
	result := make([]*process.Process, 0)
	for _, i := range p {
		c, innerErr := i.CmdlineSlice()
		if innerErr != nil || len(c) <= 0 {
			continue
		}
		if c[0] == cmdline {
			result = append(result, i)
		}
	}
	return result, nil
}

// GetProcessCPUUsage 获取进程的CPU使用率
func GetProcessCPUUsage(pid int32) (float64, error) {
	p, err := process.NewProcess(pid)
	if err != nil {
		return 0, err
	}
	return p.CPUPercent()
}
