//go:build unix && !aix && !solaris

package hotnews

import (
	"os"
	"syscall"
)

var cacheRootLockUnsupported error

func acquireCacheRootLock(root *os.File) (func() error, error) {
	// Cache I/O is best effort, so contention is a miss/skip rather than a
	// reason to delay a caller beyond its context deadline.
	if err := flockCacheRoot(root, syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
		return nil, err
	}
	return func() error {
		return flockCacheRoot(root, syscall.LOCK_UN)
	}, nil
}

func flockCacheRoot(root *os.File, operation int) error {
	for {
		err := syscall.Flock(int(root.Fd()), operation)
		if err == syscall.EINTR {
			continue
		}
		return err
	}
}
