//go:build linux

package pidfd_test

import (
	"context"
	"fmt"
	"io"
	"os"
	"os/exec"
	"time"

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

func ExampleProcess() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	command := exec.CommandContext(ctx, "/bin/cat")
	input, err := command.StdinPipe()
	if err != nil {
		panic(err)
	}

	if err := command.Start(); err != nil {
		panic(err)
	}

	defer func() {
		_ = command.Process.Kill()
		_ = command.Wait()
	}()

	process, err := pidfd.OpenProcess(command.Process)
	if err != nil {
		panic(err)
	}

	defer process.Close()

	if err := input.Close(); err != nil {
		panic(err)
	}

	if err := process.WaitReady(); err != nil {
		panic(err)
	}

	// Observation leaves child status and os/exec cleanup to its owner.
	if err := command.Wait(); err != nil {
		panic(err)
	}

	fmt.Println("child reaped:", command.ProcessState.Success())

	// Output: child reaped: true
}

func ExampleOpenProcess() {
	// Acquisition borrows the stable native handle and owns its duplicate.
	self, err := os.FindProcess(os.Getpid())
	if err != nil {
		panic(err)
	}

	defer func() {
		_ = self.Release()
	}()

	process, err := pidfd.OpenProcess(self)
	if err != nil {
		panic(err)
	}

	defer process.Close()

	if err := process.Signal(0); err != nil {
		panic(err)
	}

	fmt.Println("process exists")

	// Output: process exists
}

// The parent reads the report through its duplicate of the worker’s file.
//
//	worker report
func ExampleProcess_DuplicateFile() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	report, err := os.CreateTemp("", "worker-report-")
	if err != nil {
		panic(err)
	}
	defer os.Remove(report.Name())
	defer report.Close()
	if _, err := report.WriteAt([]byte("worker report\n"), 0); err != nil {
		panic(err)
	}

	command := exec.CommandContext(ctx, "/bin/cat")
	command.ExtraFiles = []*os.File{report}
	input, err := command.StdinPipe()
	if err != nil {
		panic(err)
	}
	if err := command.Start(); err != nil {
		panic(err)
	}
	defer func() {
		_ = command.Process.Kill()
		_ = command.Wait()
	}()

	process, err := pidfd.OpenProcess(command.Process)
	if err != nil {
		panic(err)
	}
	defer process.Close()

	// The first ExtraFiles entry occupies file number 3 in the worker.
	const reportFileNumber = 3
	file, err := process.DuplicateFile(reportFileNumber)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	if _, err := io.Copy(os.Stdout, file); err != nil {
		panic(err)
	}

	if err := input.Close(); err != nil {
		panic(err)
	}
	if err := command.Wait(); err != nil {
		panic(err)
	}
}
