//go:build !windows

package daemoncontrol

import (
	"fmt"
	"os"
	"syscall"

	"github.com/tidbcloud/AgentTeam/desktop/internal/profile"
)

func secureRuntimeFile(path string) error {
	return profile.SecureRuntimeFile(path)
}

func ensurePrivateRuntimeDir(path string) error {
	if err := os.MkdirAll(path, 0o700); err != nil {
		return err
	}
	return os.Chmod(path, 0o700)
}

func validatePrivateRuntimeFile(_ string, info os.FileInfo) error {
	if info.Mode().Perm()&^0o600 != 0 {
		return fmt.Errorf("permissions must not exceed 0600")
	}
	return nil
}

func publishRuntimeFile(source, target string, replace bool) error {
	if !replace {
		if _, err := os.Lstat(target); err == nil {
			return ErrDaemonAlreadyRunning
		} else if !os.IsNotExist(err) {
			return err
		}
	}
	return os.Rename(source, target)
}

func tryLockMutationFile(file *os.File) (bool, error) {
	err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
	if err == nil {
		return true, nil
	}
	if err == syscall.EWOULDBLOCK || err == syscall.EAGAIN {
		return false, nil
	}
	return false, err
}

func unlockMutationFile(file *os.File) error {
	return syscall.Flock(int(file.Fd()), syscall.LOCK_UN)
}

func syncDirectory(path string) error {
	dir, err := os.Open(path)
	if err != nil {
		return err
	}
	defer dir.Close()
	return dir.Sync()
}
