//go:build linux

package mount_test

import (
	"errors"
	"fmt"
	"os"
	"path/filepath"

	"github.com/alexfalkowski/go-linux/v2/mount"
)

// Each line gives the mount ID, filesystem type, and mount point. A tmpfs mounted at /work could appear as follows.
//
//	3000000000 tmpfs /work
func ExampleList() {
	page := mount.ListOptions{Limit: 32}
	mask := mount.MaskMount | mount.MaskMountPoint | mount.MaskFilesystemType
	for {
		ids, err := mount.List(page)
		if err != nil {
			panic(err)
		}
		if len(ids) == 0 {
			break
		}

		for _, id := range ids {
			info, err := mount.Stat(id, mount.StatOptions{Mask: mask})
			if errors.Is(err, os.ErrNotExist) {
				continue // The mount disappeared after List.
			}
			if err != nil {
				panic(err)
			}
			if info.Mask&mask == mask {
				fmt.Printf("%d %s %s\n", info.ID, info.FilesystemType, info.MountPoint)
			}
		}
		page.After = ids[len(ids)-1]
	}
}

// The detached mount reports its execution restriction before attachment.
//
//	noexec: true
func ExampleConfig() {
	// Run in a caller-provided isolated mount namespace with CAP_SYS_ADMIN.
	// This example is executed by the namespace integration fixture.
	config, err := mount.Open("tmpfs")
	if err != nil {
		panic(err)
	}

	defer config.Close()

	if err := config.SetString("size", "1m"); err != nil {
		panic(err) // errors.As(err, &mountError) exposes kernel diagnostics.
	}

	if err := config.SetFlag("rw"); err != nil {
		panic(err)
	}

	if err := config.Create(); err != nil {
		panic(err)
	}

	handle, err := config.Mount(mount.NoSUID | mount.NoDev)
	if err != nil {
		panic(err)
	}

	defer handle.Close()

	if err := handle.SetAttributes(mount.AttributeChange{Set: mount.NoExec}); err != nil {
		panic(err)
	}

	attributes, err := handle.Attributes()
	if err != nil {
		panic(err)
	}
	fmt.Println("noexec:", attributes&mount.NoExec != 0)
}

// Reading the file on the attached tmpfs returns its contents.
//
//	hello
func ExampleHandle_Attach() {
	// The caller has already isolated its mount namespace and made propagation
	// private. This example runs only in the namespace integration fixture.
	path, err := os.MkdirTemp("", "go-linux-mount-example-")
	if err != nil {
		panic(err)
	}

	defer os.RemoveAll(path)

	config, err := mount.Open("tmpfs")
	if err != nil {
		panic(err)
	}

	defer config.Close()

	if err := config.Create(); err != nil {
		panic(err)
	}

	handle, err := config.Mount(mount.NoSUID | mount.NoDev | mount.NoExec)
	if err != nil {
		panic(err)
	}

	defer handle.Close()

	if err := handle.Attach(nil, path); err != nil {
		panic(err)
	}

	// Attachment persists after handle.Close. Explicit unmount belongs to the
	// caller; run it before removing the temporary directory.
	defer func() {
		if err := mount.Unmount(path, mount.Detach); err != nil {
			panic(err)
		}
	}()

	name := filepath.Join(path, "hello")
	if err := os.WriteFile(name, []byte("hello\n"), 0o600); err != nil {
		panic(err)
	}
	contents, err := os.ReadFile(name)
	if err != nil {
		panic(err)
	}
	fmt.Print(string(contents))
}

// After the kernel accepts the new tmpfs size, the example reports the applied setting.
//
//	tmpfs size set to 2m
func ExamplePick() {
	// Run in a caller-provided isolated mount namespace with private propagation.
	path, err := os.MkdirTemp("", "go-linux-reconfigure-")
	if err != nil {
		panic(err)
	}
	defer os.RemoveAll(path)

	creation, err := mount.Open("tmpfs")
	if err != nil {
		panic(err)
	}
	defer creation.Close()

	if err := creation.Create(); err != nil {
		panic(err)
	}
	handle, err := creation.Mount(0)
	if err != nil {
		panic(err)
	}
	defer handle.Close()

	if err := handle.Attach(nil, path); err != nil {
		panic(err)
	}
	defer func() {
		if err := mount.Unmount(path, mount.Detach); err != nil {
			panic(err)
		}
	}()

	config, err := mount.Pick(nil, path, mount.PickNoFollow|mount.PickNoAutomount)
	if err != nil {
		panic(err)
	}
	defer config.Close()

	const size = "2m"
	if err := config.SetString("size", size); err != nil {
		panic(err)
	}
	if err := config.Reconfigure(); err != nil {
		panic(err)
	}
	fmt.Println("tmpfs size set to", size)
}

// After switching roots and detaching the old root, the child prints its working directory.
//
//	/
func ExamplePivotRoot() {
	// Run in a dedicated mount namespace child. Make / recursively private
	// with SetPropagation before attaching rootfs, then create an empty
	// rootfs/old-root directory inside that mount.
	if err := mount.PivotRoot("rootfs", "rootfs/old-root"); err != nil {
		panic(err)
	}
	if err := os.Chdir("/"); err != nil {
		panic(err)
	}
	if err := mount.Unmount("/old-root", mount.Detach); err != nil {
		panic(err)
	}
	if err := os.Remove("/old-root"); err != nil {
		panic(err)
	}
	cwd, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	fmt.Println(cwd)
}
