// NKSC1-c8c7ea42327292095dea8150adbebc85-0708f3a4174e426d0d2ad28718b26adb4894e3d58893d8e7340ae63a514fbf41

//go:build linux || darwin

package license

import (
	"context"
	"errors"
	"os"
	"os/exec"
	"runtime"
	"strings"
	"time"

	"golang.org/x/sys/unix"
)

func platformHardwareID() (string, error) {
	if runtime.GOOS == "linux" {
		for _, path := range []string{"/etc/machine-id", "/var/lib/dbus/machine-id"} {
			if data, err := os.ReadFile(path); err == nil && len(strings.TrimSpace(string(data))) >= 16 {
				return strings.TrimSpace(string(data)), nil
			}
		}
	} else {
		ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
		defer cancel()
		data, err := exec.CommandContext(ctx, "/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice").Output()
		if err != nil {
			return "", err
		}
		for _, line := range strings.Split(string(data), "\n") {
			if strings.Contains(line, `"IOPlatformUUID"`) {
				parts := strings.SplitN(line, "=", 2)
				if len(parts) == 2 {
					return strings.Trim(strings.TrimSpace(parts[1]), `"`), nil
				}
			}
		}
	}
	return "", errors.New("stable system identity unavailable")
}

// Unix uses owner-only files outside the app directory. An administrator with
// a complete VPS snapshot can still clone these; no hardware-attestation claim.
func protectDeviceState(data []byte, _ string) ([]byte, error)   { return data, nil }
func unprotectDeviceState(data []byte, _ string) ([]byte, error) { return data, nil }
func lockDeviceFile(f *os.File) error                            { return unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB) }
func unlockDeviceFile(f *os.File)                                { _ = unix.Flock(int(f.Fd()), unix.LOCK_UN) }
