package utils

import (
	"os"
	"strings"
)

var (
	PATH = make([]string, 0, 128)
)

func parsePath() {
	envPath, have := os.LookupEnv("PATH")
	if !have {
		return
	}
	envPath = strings.Trim(envPath, "\n")
	plist := strings.Split(envPath, ":")
	clear(PATH)
	for _, v := range plist {
		PATH = append(PATH, strings.TrimSuffix(v, "\n"))
	}
}

// FindCmd 查询命令是否存在
func FindCmd(cmd string) *string {
	if len(PATH) == 0 {
		parsePath()
		if len(PATH) == 0 {
			return nil
		}
	}
	for _, v := range PATH {
		target := v + "/" + cmd
		stat, err := os.Stat(target)
		if err != nil {
			continue
		}
		p := stat.Mode().Perm()
		if p.IsDir() {
			continue
		}
		if p&0111 != 0 {
			return &target
		}
	}
	return nil
}
