"""Descriptor-based access to mail trees writable by other local accounts."""

import os
import stat
from contextlib import contextmanager
from pathlib import Path


@contextmanager
def directory_fd(path: Path, *, create: bool = False, mode: int = 0o700):
    """Pin every directory component; never traverse a symbolic link."""
    path = Path(path).absolute()
    if ".." in path.parts:
        raise ValueError("Parent traversal is not allowed")
    fd = os.open(path.anchor, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC)
    try:
        for component in path.parts[1:]:
            if create:
                try:
                    os.mkdir(component, mode=mode, dir_fd=fd)
                except FileExistsError:
                    pass
            child = os.open(component, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | os.O_CLOEXEC, dir_fd=fd)
            os.close(fd)
            fd = child
        yield fd
    finally:
        os.close(fd)


def regular_file_fd(parent_fd: int, name: str, flags: int, mode: int = 0o600) -> int:
    """Open a single-link regular file without truncating before validation."""
    if not name or name in {".", ".."} or "/" in name or "\\" in name:
        raise ValueError("Invalid file name")
    fd = os.open(name, (flags & ~os.O_TRUNC) | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, mode, dir_fd=parent_fd)
    try:
        info = os.fstat(fd)
        if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
            raise OSError("Refusing non-regular or multiply linked file")
        if flags & os.O_TRUNC:
            os.ftruncate(fd, 0)
        return fd
    except BaseException:
        os.close(fd)
        raise
