package utils

import (
	"os"
	"path/filepath"
	"strings"
)

const (
	DefaultPATH = "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
)

// DetectCmd 探测是否有指定的命令
func DetectCmd(c string) (bool, string) {
	path := os.Getenv("PATH")
	if path == "" {
		path = DefaultPATH
	}
	prefix := strings.Split(strings.ReplaceAll(path, " ", ""), ":")
	for _, p := range prefix {
		fullPath := filepath.Join(p, c)
		finfo, err := os.Stat(fullPath)
		if err != nil {
			continue
		}
		if !finfo.IsDir() && finfo.Mode()&0111 != 0 {
			return true, fullPath
		}
	}
	return false, ""
}
