package host_info

import (
	"agent-wdd/log"
	"bufio"
	"os"
	"os/exec"
	"regexp"
	"runtime"
	"strings"
)

func (os *OS) SaveConfig() {
	log.Info("Saving INFO => OS !")

	ConfigCache.Agent.OS = *os
	SaveConfig()
}

func (o *OS) Gather() {

	log.Info("Gathering INFO => OS !")

	// 获取主机名
	if hostname, err := os.Hostname(); err == nil {
		o.Hostname = hostname
	}

	o.OsType = "linux"    // 固定为linux
	o.IsUbuntuType = true // 默认为ubuntu

	// 解析系统信息
	file, err := os.Open("/etc/os-release")
	if err == nil {
		defer file.Close()
		scanner := bufio.NewScanner(file)
		osInfo := make(map[string]string)

		for scanner.Scan() {
			line := scanner.Text()
			if parts := strings.SplitN(line, "=", 2); len(parts) == 2 {
				key := parts[0]
				value := strings.Trim(parts[1], `"`)
				osInfo[key] = value
			}
		}

		//utils.BeautifulPrint(osInfo)

		// 获取操作系统名称
		if name, ok := osInfo["PRETTY_NAME"]; ok {
			o.OsName = name
		}

		// 获取系统家族
		if id, ok := osInfo["ID"]; ok {
			o.OsFamily = id
		}

		// 判定系统是否是ubuntu类型
		if o.OsFamily == "ubuntu" || o.OsFamily == "debian" || o.OsFamily == "linuxmint" || o.OsFamily == "elementary" || o.OsFamily == "pop" || o.OsFamily == "mint" || o.OsFamily == "kali" || o.OsFamily == "deepin" || o.OsFamily == "zorin" {
			o.IsUbuntuType = true
		} else {
			// 设置系统为非ubuntus
			o.IsUbuntuType = false
		}

		// 获取系统版本
		if version, ok := osInfo["VERSION_ID"]; ok {
			o.OsVersion = version
		} else {
			// 针对RedHat系特殊处理
			if o.OsFamily == "centos" || o.OsFamily == "rhel" {

				// 针对RedHat系特殊处理
				if data, err := os.ReadFile("/etc/redhat-release"); err == nil {
					re := regexp.MustCompile(`\d+(\.\d+)+`)
					if match := re.FindString(string(data)); match != "" {
						o.OsVersion = match
					}
				}
			}
		}
	}

	// 获取内核版本
	if out, err := exec.Command("uname", "-r").Output(); err == nil {
		o.Kernel = strings.TrimSpace(string(out))
	}

	// 获取系统架构
	o.Arch = runtime.GOARCH

	// 获取系统发行版代号
	if o.IsUbuntuType {
		o.OSReleaseCode = judgeUbuntuReleaseFromOsVersion(o.OsVersion)
	} else {
		o.OSReleaseCode = "non-ubuntu"
	}

}

func judgeUbuntuReleaseFromOsVersion(osVersion string) string {

	switch osVersion {
	case "16.04":
		return "xenial"
	case "18.04":
		return "bionic"
	case "20.04":
		return "focal"
	case "22.04":
		return "jammy"
	default:
		return "ubuntu-unknown"
	}
}
