//go:build linux

package main

// The Linux directory walker: openat / getdents64 / fstatat on file descriptors, with the entry
// names passed to the kernel straight from the getdents buffer (they are NUL-terminated there), so
// a file costs one fstatat and no allocation. Directories are opened with O_NOFOLLOW (a symbolic
// link is never followed) and a directory on another device (a mount point) is not entered.

import (
	"syscall"
	"unsafe"
)

const (
	atSymlinkNofollow = 0x100
	dtUnknown         = 0
	dtDir             = 4
	dtReg             = 8
	openDirFlags      = syscall.O_RDONLY | syscall.O_DIRECTORY | syscall.O_NOFOLLOW | syscall.O_CLOEXEC | syscall.O_NONBLOCK
)

func devOf(path string) (uint64, bool) {
	var st syscall.Stat_t
	if err := syscall.Stat(path, &st); err != nil {
		return 0, false
	}
	return uint64(st.Dev), true
}

func fstatatRaw(dirfd int, name *byte, st *syscall.Stat_t) syscall.Errno {
	_, _, e := syscall.Syscall6(sysFstatat, uintptr(dirfd), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(st)), atSymlinkNofollow, 0, 0)
	return e
}

func openatRaw(dirfd int, name *byte) (int, syscall.Errno) {
	fd, _, e := syscall.Syscall6(syscall.SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(name)), openDirFlags, 0, 0, 0)
	return int(fd), e
}

// walkTree returns the allocated bytes and the number of files below root (its own device only).
func walkTree(root string, dev uint64, acc *scanAcc) (int64, int64) {
	fd, err := syscall.Open(root, openDirFlags, 0)
	if err != nil {
		return 0, 0
	}
	return walkFd(fd, root, 0, dev, acc)
}

func walkFd(fd int, path string, depth int, dev uint64, acc *scanAcc) (bytes, files int64) {
	defer syscall.Close(fd)
	buf := acc.buf(depth)
	var st syscall.Stat_t
	for !acc.stopped {
		n, err := syscall.ReadDirent(fd, buf)
		if err == syscall.EINTR {
			continue
		}
		if err != nil || n <= 0 {
			break
		}
		for off := 0; off < n; {
			// struct linux_dirent64 { u64 ino; s64 off; u16 reclen; u8 type; char name[]; }
			if off+19 > n {
				break
			}
			reclen := int(*(*uint16)(unsafe.Pointer(&buf[off+16])))
			typ := buf[off+18]
			if reclen <= 0 || off+reclen > n {
				break
			}
			nameStart, recEnd := off+19, off+reclen
			nameEnd := nameStart
			for nameEnd < recEnd && buf[nameEnd] != 0 {
				nameEnd++
			}
			off = recEnd
			if nameEnd == nameStart || nameEnd >= recEnd { // empty, or not NUL-terminated inside its record
				continue
			}
			name := buf[nameStart:nameEnd]
			namePtr := &buf[nameStart]
			if (len(name) == 1 && name[0] == '.') || (len(name) == 2 && name[0] == '.' && name[1] == '.') {
				continue
			}
			if !acc.tick() {
				break
			}
			if typ != dtDir && typ != dtReg && typ != dtUnknown {
				continue // symbolic links, sockets, devices: no space worth counting
			}
			if fstatatRaw(fd, namePtr, &st) != 0 {
				continue
			}
			switch st.Mode & syscall.S_IFMT {
			case syscall.S_IFREG:
				sz := st.Blocks * 512
				bytes += sz
				files++
				if sz >= acc.fileMin {
					acc.file(joinPath(path, string(name)), sz)
				}
			case syscall.S_IFDIR:
				if uint64(st.Dev) != dev || depth+1 > scanMaxDepth {
					continue // another filesystem (a mount point) or too deep
				}
				bytes += st.Blocks * 512
				cfd, e := openatRaw(fd, namePtr)
				if e != 0 {
					continue
				}
				cb, cf := walkFd(cfd, joinPath(path, string(name)), depth+1, dev, acc)
				bytes += cb
				files += cf
			}
		}
	}
	acc.dir(path, depth, bytes, files)
	return bytes, files
}
