//go:build windows

package winproc

import (
	"os/exec"
	"syscall"

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

// CREATE_NO_WINDOW. Spelled out so callers don't drag in
// golang.org/x/sys/windows for one constant.
const createNoWindow uint32 = 0x08000000

// localSystemSID is the well-known SID for NT AUTHORITY\SYSTEM. Used to
// distinguish MSI deferred custom actions (which run as LocalSystem) from
// elevated admin invocations — the executor's IsRoot() returns true for
// both, so we can't reuse it for this discrimination.
const localSystemSID = "S-1-5-18"

// HideWindow tells the child not to allocate a console. Safe to call
// twice or on a cmd whose SysProcAttr is already set: HideWindow is
// merged, not overwritten, and CREATE_NO_WINDOW is OR'd into
// CreationFlags. Without this, every powershell/cmd/.cmd subprocess
// Go spawns under Task Scheduler flashes a console window.
func HideWindow(cmd *exec.Cmd) {
	if cmd == nil {
		return
	}
	if cmd.SysProcAttr == nil {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
	}
	cmd.SysProcAttr.HideWindow = true
	cmd.SysProcAttr.CreationFlags |= createNoWindow
}

// IsLocalSystem reports whether the current process is running as
// NT AUTHORITY\SYSTEM. Returns false on any error — a misread SID
// degrades to the inline-install path, which is the existing behavior.
func IsLocalSystem() bool {
	tu, err := windows.GetCurrentProcessToken().GetTokenUser()
	if err != nil {
		return false
	}
	return tu.User.Sid.String() == localSystemSID
}
