//go:build linux

package mount

import (
	"os"
	"sync"

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

// Open acquires a close-on-exec filesystem configuration context with fsopen.
// The caller owns the result and must close it. No configuration, creation,
// attachment, or namespace entry occurs implicitly. Filesystem names use kernel
// validation; embedded NUL bytes fail with EINVAL. Errors wrap os.PathError and
// preserve errno identity. On error no descriptor is retained and result is nil.
func Open(filesystem string) (*Config, error) {
	fd, err := unix.Fsopen(filesystem, unix.FSOPEN_CLOEXEC)
	if err != nil {
		return nil, &os.PathError{Op: "fsopen", Path: filesystem, Err: err}
	}
	return &Config{file: os.NewFile(uintptr(fd), filesystem)}, nil
}

// PickFlags controls path lookup for Pick. Zero uses the kernel defaults for
// symlinks and automounts. Unknown bits match os.ErrInvalid.
type PickFlags uint32

// PickNoFollow leaves a final symlink unresolved during Pick.
const PickNoFollow PickFlags = unix.FSPICK_SYMLINK_NOFOLLOW

// PickNoAutomount suppresses automount of the final path component during Pick.
const PickNoAutomount PickFlags = unix.FSPICK_NO_AUTOMOUNT

// Pick acquires a close-on-exec Config for reconfiguring an existing filesystem
// with fspick. The target must resolve to a mount's root. Changes made later
// through Reconfigure apply to the filesystem, including its other mounts.
//
// dir is borrowed for the call. Nil selects the current working directory.
// Absolute paths ignore dir during kernel lookup. An empty path selects dir
// itself and requires a nonnil dir. Pick uses ordinary kernel path resolution.
// Unknown flags and empty paths without dir match os.ErrInvalid before access.
// Errors wrap os.PathError. On failure Pick returns nil and retains no new
// descriptor. On success the caller must close the Config independently of dir.
func Pick(dir *os.File, path string, flags PickFlags) (*Config, error) {
	unknownFlags := flags & ^(PickNoFollow|PickNoAutomount) != 0
	missingDirectory := path == "" && dir == nil
	if unknownFlags || missingDirectory {
		return nil, &os.PathError{Op: "fspick", Path: path, Err: os.ErrInvalid}
	}

	options := unix.FSPICK_CLOEXEC | int(flags)
	if path == "" {
		options |= unix.FSPICK_EMPTY_PATH
	}

	var result int
	err := directoryControl(dir, "fspick", path, func(fd int) error {
		var err error
		result, err = unix.Fspick(fd, path, options)
		return err
	})
	if err != nil {
		return nil, err
	}
	return &Config{file: os.NewFile(uintptr(result), path)}, nil
}

// Config owns one filesystem configuration descriptor and implements
// io.Closer. Do not copy it after first use. Descriptor access, including Close
// and diagnostic reads, is serialized. The same lock protects collection of
// diagnostics after a failure. Pending warnings from earlier calls can also be
// included. Linux owns configuration phase validation and can make the context
// unusable after a failed Create or Reconfigure. Callers coordinate sequences
// of operations.
//
// A zero Config owns nothing. Operations on it with valid arguments match
// os.ErrInvalid.
type Config struct {
	file *os.File
	mu   sync.Mutex
}

// SetFlag supplies a parameter with no value using FSCONFIG_SET_FLAG. It is
// distinct from SetString(key, ""). Unknown parameters and phase errors are
// kernel-defined. On syscall failure an Error preserves available diagnostics;
// the existing Config remains caller-owned, including after failure.
func (c *Config) SetFlag(key string) error {
	c.mu.Lock()
	defer c.mu.Unlock()

	return c.configure("fsconfig_set_flag", func(fd int) error {
		return unix.FsconfigSetFlag(fd, key)
	})
}

// SetString supplies a string parameter with FSCONFIG_SET_STRING. Empty values
// are permitted; NUL bytes in key/value match EINVAL. Filesystem validation and
// failure ownership/diagnostics follow SetFlag. No option-list parsing occurs.
func (c *Config) SetString(key, value string) error {
	c.mu.Lock()
	defer c.mu.Unlock()

	return c.configure("fsconfig_set_string", func(fd int) error {
		return unix.FsconfigSetString(fd, key, value)
	})
}

// SetBinary supplies a blob parameter with FSCONFIG_SET_BINARY. Linux copies
// value during the call, including embedded NUL bytes. Keep the slice unchanged
// until the call returns. Sizes outside 1 byte through 1 MiB fail with EINVAL
// before descriptor access. Filesystem support and diagnostics follow SetFlag.
func (c *Config) SetBinary(key string, value []byte) error {
	const maxSize = 1 << 20
	if len(value) == 0 || len(value) > maxSize {
		return &os.PathError{Op: "fsconfig_set_binary", Path: "mount", Err: unix.EINVAL}
	}

	c.mu.Lock()
	defer c.mu.Unlock()

	return c.configure("fsconfig_set_binary", func(fd int) error {
		return unix.FsconfigSetBinary(fd, key, value)
	})
}

// SetPath supplies a filename parameter using FSCONFIG_SET_PATH. The
// filesystem determines whether and how it is resolved. Nil dir supplies the
// current working directory as the base. An empty path uses
// FSCONFIG_SET_PATH_EMPTY to refer to dir itself, which may be a nondirectory
// file. An empty path with nil dir matches os.ErrInvalid before descriptor access.
// A nonnil dir is borrowed for the call. It remains caller-owned, even if the
// filesystem retains a reference to a resolved object. Diagnostics follow SetFlag.
func (c *Config) SetPath(key string, dir *os.File, path string) error {
	if path == "" && dir == nil {
		return &os.PathError{Op: "fsconfig_set_path", Path: path, Err: os.ErrInvalid}
	}

	c.mu.Lock()
	defer c.mu.Unlock()

	return c.configure("fsconfig_set_path", func(fd int) error {
		if dir == nil {
			return unix.FsconfigSetPath(fd, key, path, unix.AT_FDCWD)
		}
		return control(dir, func(atfd int) error {
			if path == "" {
				return unix.FsconfigSetPathEmpty(fd, key, path, atfd)
			}
			return unix.FsconfigSetPath(fd, key, path, atfd)
		})
	})
}

// SetFile supplies an open file as a parameter with FSCONFIG_SET_FD. The
// file is borrowed during the call and remains caller-owned on success or
// failure. A filesystem may retain its own reference to the supplied object.
// Nil file matches os.ErrInvalid before descriptor access. Diagnostics follow
// SetFlag.
func (c *Config) SetFile(key string, file *os.File) error {
	if file == nil {
		return &os.PathError{Op: "fsconfig_set_fd", Path: "mount", Err: os.ErrInvalid}
	}

	c.mu.Lock()
	defer c.mu.Unlock()

	return c.configure("fsconfig_set_fd", func(fd int) error {
		return control(file, func(value int) error {
			return unix.FsconfigSetFd(fd, key, value)
		})
	})
}

// Create prepares the filesystem with FSCONFIG_CMD_CREATE. The kernel may
// reuse an existing filesystem instance; this is not exclusive creation or an
// isolation guarantee. Mount remains a separate step. Errors and ownership
// follow SetFlag; successful configuration is not rolled back on later failure.
func (c *Config) Create() error {
	c.mu.Lock()
	defer c.mu.Unlock()

	return c.configure("fsconfig_create", unix.FsconfigCreate)
}

// Reconfigure applies pending parameters to an existing filesystem with
// FSCONFIG_CMD_RECONFIGURE. Use a Config returned by Pick or one that has
// successfully acquired a Handle with Mount. It changes the shared filesystem.
// On success the context can accept a fresh set of reconfiguration parameters.
// A failure can leave partial changes and make the context unusable. The
// caller still owns it. Diagnostics follow SetFlag.
func (c *Config) Reconfigure() error {
	c.mu.Lock()
	defer c.mu.Unlock()

	return c.configure("fsconfig_reconfigure", unix.FsconfigReconfigure)
}

// Mount acquires a detached close-on-exec mount with fsmount. Create must have
// succeeded. Zero attributes adds no restrictions; unknown bits match
// os.ErrInvalid. The caller owns the new Handle and the existing Config
// independently. Failure returns nil, retains no new descriptor, and leaves
// Config open. A kernel failure can advance configuration state even without a
// returned handle. Available diagnostics are preserved as for SetFlag.
func (c *Config) Mount(attributes Attributes) (*Handle, error) {
	c.mu.Lock()
	defer c.mu.Unlock()

	if attributes & ^supportedAttributes != 0 {
		return nil, &os.PathError{Op: "fsmount", Path: "mount", Err: os.ErrInvalid}
	}
	var result int
	err := c.configure("fsmount", func(fd int) error {
		var err error
		result, err = unix.Fsmount(fd, unix.FSMOUNT_CLOEXEC, int(attributes))
		return err
	})
	if err != nil {
		return nil, err
	}
	return &Handle{file: os.NewFile(uintptr(result), "mount")}, nil
}

// Diagnostics drains the currently available kernel records. No records returns
// nil, nil. Partial records accompany retrieval errors. Failed configuration
// methods already drain into Error; those messages are not returned again.
// The bounded kernel queue can overwrite earlier records. Reads grow from 4 KiB
// to 1 MiB on EMSGSIZE; larger messages return EMSGSIZE without consuming that
// record on Linux 7.0+. No lossless log or fixed producer size is promised.
func (c *Config) Diagnostics() ([]Diagnostic, error) {
	c.mu.Lock()
	defer c.mu.Unlock()

	var records []Diagnostic
	err := fileControl(c.file, "fscontext_read", "mount", func(fd int) error {
		var err error
		records, err = readDiagnostics(fd)
		return err
	})
	return records, err
}

// Close releases the configuration context, including its pending diagnostics.
// It leaves previously acquired handles and attached mounts intact. Repeated
// Close matches os.ErrClosed. It waits for in-flight methods to finish.
func (c *Config) Close() error {
	c.mu.Lock()
	defer c.mu.Unlock()

	return c.file.Close()
}

// configure runs with mu held and collects diagnostics before another method
// can change the queue. Reading within Control also pins lifetime throughout.
func (c *Config) configure(op string, operation func(int) error) error {
	return fileControl(c.file, op, "mount", func(fd int) error {
		if err := operation(fd); err != nil {
			records, diagnosticErr := readDiagnostics(fd)
			return &Error{Err: os.NewSyscallError(op, err), Diagnostics: records, DiagnosticError: diagnosticErr}
		}
		return nil
	})
}
