//go:build linux

package seccomp_test

import (
	"fmt"
	"io"
	"os"
	"runtime"
	"testing"

	"github.com/alexfalkowski/go-linux/v2/internal/test"
	"github.com/alexfalkowski/go-linux/v2/seccomp"
)

func ExampleNew() {
	architecture, err := seccomp.NativeArchitecture()
	if err != nil {
		fmt.Println(err)
		return
	}
	// Construction is safe in an ordinary caller. Loading is irreversible and
	// belongs on a locked goroutine in a disposable child during development.
	filter, err := seccomp.New(architecture, []seccomp.Instruction{
		{Code: seccomp.Return, K: uint32(seccomp.Allow)},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(filter != nil)
	// Output: true
}

func ExampleActionAvailable() {
	available, err := seccomp.ActionAvailable(seccomp.KillProcess)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(available)
	// Output: true
}

// The worker receives the value supplied by the supervisor.
//
//	12345
func ExampleFilter_Listen() {
	architecture, err := seccomp.NativeArchitecture()
	if err != nil {
		panic(err)
	}
	filter, err := seccomp.New(architecture, []seccomp.Instruction{
		{Code: seccomp.LoadWord, K: seccomp.SyscallOffset},
		{Code: seccomp.JumpEqual, K: test.ProcessGroupSyscall, Jf: 1}, // Native getpgid number.
		{Code: seccomp.Return, K: uint32(seccomp.Notify)},
		{Code: seccomp.Return, K: uint32(seccomp.Allow)},
	})
	if err != nil {
		panic(err)
	}

	listeners := make(chan *seccomp.Listener, 1)
	values := make(chan int, 1)
	go func() {
		runtime.LockOSThread() // Keep policy on this worker until it exits.
		listener, err := filter.Listen(seccomp.Options{
			Synchronization: seccomp.CallingThread,
			Privileges:      seccomp.SetNoNewPrivileges,
		})
		if err != nil {
			panic(err)
		}
		listeners <- listener
		value, err := test.ProcessGroup(0) // Calls getpgid on the restricted thread.
		if err != nil {
			panic(err)
		}
		values <- value
	}()

	listener := <-listeners
	defer listener.Close()
	request, err := listener.Receive()
	if err != nil {
		panic(err)
	}
	if err := listener.Respond(request.ID, 12345); err != nil {
		panic(err)
	}
	fmt.Println(<-values)
}

func TestListenExample(t *testing.T) {
	test.RequireNotification(t)
	test.RequireExampleOutput(t, ExampleFilter_Listen, "12345")
}

// The worker reads the first byte from the injected /dev/zero file.
//
//	0
func ExampleListener_AddFileAndRespond() {
	// The supervisor opens the file it intends to make available to the worker.
	source, err := os.Open("/dev/zero")
	if err != nil {
		panic(err)
	}
	defer source.Close()

	architecture, err := seccomp.NativeArchitecture()
	if err != nil {
		panic(err)
	}
	filter, err := seccomp.New(architecture, []seccomp.Instruction{
		{Code: seccomp.LoadWord, K: seccomp.SyscallOffset},
		{Code: seccomp.JumpEqual, K: test.DupSyscall, Jf: 1},
		{Code: seccomp.Return, K: uint32(seccomp.Notify)},
		{Code: seccomp.Return, K: uint32(seccomp.Allow)},
	})
	if err != nil {
		panic(err)
	}

	listeners := make(chan *seccomp.Listener, 1)
	bytesRead := make(chan byte, 1)
	go func() {
		runtime.LockOSThread()
		listener, err := filter.Listen(seccomp.Options{
			Synchronization: seccomp.CallingThread,
			Privileges:      seccomp.SetNoNewPrivileges,
		})
		if err != nil {
			panic(err)
		}
		listeners <- listener

		descriptor, err := test.DupMissingDescriptor()
		if err != nil {
			panic(err)
		}
		file := os.NewFile(uintptr(descriptor), "injected")
		defer file.Close()
		var data [1]byte
		if _, err := io.ReadFull(file, data[:]); err != nil {
			panic(err)
		}
		bytesRead <- data[0]
	}()

	listener := <-listeners
	defer listener.Close()
	request, err := listener.Receive()
	if err != nil {
		panic(err)
	}
	if _, err := listener.AddFileAndRespond(request.ID, source, seccomp.FileOptions{}); err != nil {
		panic(err)
	}
	fmt.Println(<-bytesRead)
}

func TestAddFileAndRespondExample(t *testing.T) {
	test.RequireNotification(t)
	test.RequireExampleOutput(t, ExampleListener_AddFileAndRespond, "0")
}
