package cmd

import (
	"bytes"
	"github.com/33cn/chain33/common/log"
	"os/exec"
	"strings"
	"chain33-pai/pkg/file"
	"os"
	"io"
)

var cmdLog = log.New("pkg", "app")

func GetLocalArchType() string {
	cmd := exec.Command("arch")
	var buf bytes.Buffer
	cmd.Stdout = &buf
	err := cmd.Run()
	if err != nil {
		cmdLog.Error("GetLocalArchType", "err", err)
		return ""
	}
	if buf.String() != "" {
		lines := strings.Split(buf.String(), "\n")
		if len(lines) == 2 {
			return strings.Trim(lines[0], " ")
		}
	}
	return ""
}

func GetUUID() string {
	uuid := GetLocalUUIDByFile()
	if uuid != "" {
		return uuid
	}
	return GetLocalUUID2()
}

func GetLocalUUIDByFile() string {
	if !file.CheckNotExist("uuid.file") {
		f,err := file.Open("uuid.file",os.O_RDONLY,0)
		if err != nil {
			cmdLog.Error("GetLocalUUIDByFile","err",err)
			return ""
		}
		defer f.Close()
		var b []byte = make([]byte,1024)
		_,err = f.Read(b)
		if err != nil && err != io.EOF {
			cmdLog.Error("GetLocalUUIDByFile","err",err)
			return ""
		}
		lines := strings.Split(string(b),"\n")
		return strings.Trim(lines[0]," ")
	}
	return ""
}

func GetLocalUUID() string {
	cmd := exec.Command("dmidecode")
	var buf, errbuf bytes.Buffer
	cmd.Stdout = &buf
	cmd.Stderr = &errbuf
	err := cmd.Start()
	if err != nil {
		cmdLog.Error("GetLocalUUID Start","err", err)
	}
	err = cmd.Wait()
	if err != nil {
		cmdLog.Error("GetLocalUUID Wait", err,err)
	}
	if buf.String() != "" {
		lines := strings.Split(buf.String(), "\n")
		if len(lines) > 0 {
			for _, l := range lines {
				if strings.Contains(l, "UUID") {
					ll := strings.Split(strings.Trim(l, "\t"),":")
					if len(ll) == 2 {
						return strings.Trim(ll[1]," ")
					}
				}
			}

		}
	}
	return ""
}

func GetLocalUUID2() string {
	cmd := exec.Command("cat","/etc/miner_sn")
	var buf, errbuf bytes.Buffer
	cmd.Stdout = &buf
	cmd.Stderr = &errbuf
	err := cmd.Start()
	if err != nil {
		cmdLog.Error("GetLocalUUID Start","err", err)
	}
	err = cmd.Wait()
	if err != nil {
		cmdLog.Error("GetLocalUUID Wait", err,err)
	}
	if buf.String() != "" {
		lines := strings.Split(buf.String(), "\n")
		if len(lines) > 0 {
			for _, l := range lines {
				if l != "" {
					return strings.Trim(l," ")
				}
			}

		}
	}
	return ""
}
