//go:build darwin
// +build darwin

package machineid

import (
	"fmt"
	"os/exec"
	"strings"
)

func getMachineID() (s string, err error) {
	var (
		buf []byte
	)
	extractID := func(lines string) (string, error) {
		for _, line := range strings.Split(lines, "\n") {
			if strings.Contains(line, "IOPlatformUUID") {
				parts := strings.SplitAfter(line, `" = "`)
				if len(parts) == 2 {
					return strings.TrimRight(parts[1], `"`), nil
				}
			}
		}
		return "", fmt.Errorf("Failed to extract 'IOPlatformUUID' value from `ioreg` output.\n%s", lines)
	}
	cmd := exec.Command("ioreg", "-rd", "-c", "IOPlatformExpertDevice")
	if buf, err = cmd.Output(); err == nil {
		s, err = extractID(string(buf))
	}
	return
}
