package instance

import (
	"errors"

	"golang.org/x/sys/windows"

	"tea.chunkbyte.com/kato/go-worm/lib/config"
)

type Guard struct {
	handle windows.Handle
}

func Acquire() (*Guard, error) {
	name, err := windows.UTF16PtrFromString(config.MutexName)
	if err != nil {
		return nil, err
	}
	h, err := windows.CreateMutex(nil, false, name)
	if h == 0 {
		return nil, err
	}
	if errors.Is(err, windows.ERROR_ALREADY_EXISTS) {
		windows.CloseHandle(h)
		return nil, errors.New("agent already running")
	}
	return &Guard{handle: h}, nil
}

func (g *Guard) Close() {
	if g == nil || g.handle == 0 {
		return
	}
	windows.CloseHandle(g.handle)
	g.handle = 0
}
