/*
   Copyright The containerd Authors.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package runc

import (
	"context"
	"errors"
	"os"
	"os/exec"
	"strings"
	"sync"
	"syscall"
	"testing"
	"time"

	specs "github.com/opencontainers/runtime-spec/specs-go"
)

func TestParseVersion(t *testing.T) {
	tests := []struct {
		doc, input string
		expected   Version
	}{
		{
			doc: "Full",
			input: `runc version 1.0.0-rc3
commit: 17f3e2a07439a024e54566774d597df9177ee216
spec: 1.0.0-rc5-dev
`,
			expected: Version{
				Runc:   "1.0.0-rc3",
				Commit: "17f3e2a07439a024e54566774d597df9177ee216",
				Spec:   "1.0.0-rc5-dev",
			},
		},
		{
			doc: "WithoutCommit",
			input: `runc version 1.0.0-rc9
spec: 1.0.1-dev
`,
			expected: Version{
				Runc: "1.0.0-rc9",
				Spec: "1.0.1-dev",
			},
		},
		{
			doc: "Oneline",
			input: `runc version 1.0.0-rc8+dev
`,
			expected: Version{
				Runc: "1.0.0-rc8+dev",
			},
		},
		{
			doc: "Garbage",
			input: `Garbage
spec: nope
`,
			expected: Version{},
		},
	}
	for _, tc := range tests {
		t.Run(tc.doc, func(t *testing.T) {
			actual := parseVersion([]byte(tc.input))
			if tc.expected != actual {
				t.Fatalf("expected: %v, actual: %v", tc.expected, actual)
			}
		})
	}
}

// TestParallelCmds exercises concurrent callers of cmdOutput and is primarily
// intended to detect unsafe shared state when run with the race detector.
func TestParallelCmds(t *testing.T) {
	// we don't need a real runc, we just want to test running a caller of cmdOutput in parallel
	rc := &Runc{Command: "/bin/true"}

	var wg sync.WaitGroup
	start := make(chan struct{})

	for i := 0; i < 256; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			<-start

			if _, err := rc.Version(context.Background()); err != nil {
				t.Error("expected parsing an empty version to pass")
			}
		}()
	}

	close(start)
	wg.Wait()
}

func TestRuncRunExit(t *testing.T) {
	ctx := context.Background()
	okRunc := &Runc{
		Command: "/bin/true",
	}

	status, err := okRunc.Run(ctx, "fake-id", "fake-bundle", &CreateOpts{})
	if err != nil {
		t.Fatalf("Unexpected error from Run: %s", err)
	}
	if status != 0 {
		t.Fatalf("Expected exit status 0 from Run, got %d", status)
	}

	failRunc := &Runc{
		Command: "/bin/false",
	}

	status, err = failRunc.Run(ctx, "fake-id", "fake-bundle", &CreateOpts{})
	if err == nil {
		t.Fatal("Expected error from Run, but got nil")
	}
	if status != 1 {
		t.Fatalf("Expected exit status 1 from Run, got %d", status)
	}
	extractedStatus := extractStatus(err)
	if extractedStatus != status {
		t.Fatalf("Expected extracted exit status %d from Run, got %d", status, extractedStatus)
	}
}

func TestRuncExecExit(t *testing.T) {
	ctx := context.Background()
	okRunc := &Runc{
		Command: "/bin/true",
	}
	err := okRunc.Exec(ctx, "fake-id", specs.Process{}, &ExecOpts{})
	if err != nil {
		t.Fatalf("Unexpected error from Exec: %s", err)
	}
	status := extractStatus(err)
	if status != 0 {
		t.Fatalf("Expected exit status 0 from Exec, got %d", status)
	}

	failRunc := &Runc{
		Command: "/bin/false",
	}

	err = failRunc.Exec(ctx, "fake-id", specs.Process{}, &ExecOpts{})
	if err == nil {
		t.Fatal("Expected error from Exec, but got nil")
	}
	status = extractStatus(err)
	if status != 1 {
		t.Fatalf("Expected exit status 1 from Exec, got %d", status)
	}

	io, err := NewSTDIO()
	if err != nil {
		t.Fatalf("Unexpected error from NewSTDIO: %s", err)
	}
	err = failRunc.Exec(ctx, "fake-id", specs.Process{}, &ExecOpts{
		IO: io,
	})
	if err == nil {
		t.Fatal("Expected error from Exec, but got nil")
	}
	status = extractStatus(err)
	if status != 1 {
		t.Fatalf("Expected exit status 1 from Exec, got %d", status)
	}
}

func TestRuncStarted(t *testing.T) {
	ctx, timeout := context.WithTimeout(context.Background(), 10*time.Second)
	defer timeout()

	dummyCommand, err := dummySleepRunc()
	if err != nil {
		t.Fatalf("Failed to create dummy sleep runc: %s", err)
	}
	defer os.Remove(dummyCommand)
	sleepRunc := &Runc{
		Command: dummyCommand,
	}

	var wg sync.WaitGroup
	defer wg.Wait()

	started := make(chan int)
	wg.Add(1)
	go func() {
		defer wg.Done()
		interrupt(ctx, t, started)
	}()
	status, err := sleepRunc.Run(ctx, "fake-id", "fake-bundle", &CreateOpts{
		Started: started,
	})
	if err == nil {
		t.Fatal("Expected error from Run, but got nil")
	}
	if status != -1 {
		t.Fatalf("Expected exit status 0 from Run, got %d", status)
	}

	started = make(chan int)
	wg.Add(1)
	go func() {
		defer wg.Done()
		interrupt(ctx, t, started)
	}()
	err = sleepRunc.Exec(ctx, "fake-id", specs.Process{}, &ExecOpts{
		Started: started,
	})
	if err == nil {
		t.Fatal("Expected error from Exec, but got nil")
	}
	status = extractStatus(err)
	if status != -1 {
		t.Fatalf("Expected exit status -1 from Exec, got %d", status)
	}

	started = make(chan int)
	wg.Add(1)
	go func() {
		defer wg.Done()
		interrupt(ctx, t, started)
	}()
	io, err := NewSTDIO()
	if err != nil {
		t.Fatalf("Unexpected error from NewSTDIO: %s", err)
	}
	err = sleepRunc.Exec(ctx, "fake-id", specs.Process{}, &ExecOpts{
		IO:      io,
		Started: started,
	})
	if err == nil {
		t.Fatal("Expected error from Exec, but got nil")
	}
	status = extractStatus(err)
	if status != -1 {
		t.Fatalf("Expected exit status 1 from Exec, got %d", status)
	}
}

func extractStatus(err error) int {
	if err == nil {
		return 0
	}
	var exitError *ExitError
	if errors.As(err, &exitError) {
		return exitError.Status
	}
	return -1
}

// interrupt waits for the pid over the started channel then sends a
// SIGINT to the process.
func interrupt(ctx context.Context, t *testing.T, started <-chan int) {
	select {
	case <-ctx.Done():
		t.Fatal("Timed out waiting for started message")
	case pid, ok := <-started:
		if !ok {
			t.Fatal("Started channel closed without sending pid")
		}
		process, _ := os.FindProcess(pid)
		defer process.Release()
		err := process.Signal(syscall.SIGINT)
		if err != nil {
			t.Fatalf("Failed to send SIGINT to %d: %s", pid, err)
		}
	}
}

// dummySleepRunc creates s simple script that just runs `sleep 10` to replace
// runc for testing process that are longer running.
func dummySleepRunc() (_ string, err error) {
	fh, err := os.CreateTemp("", "*.sh")
	if err != nil {
		return "", err
	}
	defer func() {
		if err != nil {
			os.Remove(fh.Name())
		}
	}()
	_, err = fh.Write([]byte("#!/bin/sh\nexec /bin/sleep 10"))
	if err != nil {
		return "", err
	}
	err = fh.Close()
	if err != nil {
		return "", err
	}
	err = os.Chmod(fh.Name(), 0o755)
	if err != nil {
		return "", err
	}
	return fh.Name(), nil
}

func TestCommandWorkDir(t *testing.T) {
	ctx := context.Background()

	t.Run("WorkDir is unset", func(t *testing.T) {
		r := &Runc{}
		cmd := r.command(ctx, "list")
		if cmd.Dir != "" {
			t.Fatalf("expected empty cmd.Dir, got %q", cmd.Dir)
		}
	})

	t.Run("WorkDir is set", func(t *testing.T) {
		dir := t.TempDir()
		r := &Runc{WorkDir: dir}
		cmd := r.command(ctx, "list")
		if cmd.Dir != dir {
			t.Fatalf("expected cmd.Dir %q, got %q", dir, cmd.Dir)
		}
	})
}

func TestCreateArgs(t *testing.T) {
	o := &CreateOpts{}
	args, err := o.args()
	if err != nil {
		t.Fatal(err)
	}
	if len(args) != 0 {
		t.Fatal("args should be empty")
	}
	o.ExtraArgs = []string{"--other"}
	args, err = o.args()
	if err != nil {
		t.Fatal(err)
	}
	if len(args) != 1 {
		t.Fatal("args should have 1 arg")
	}
	if a := args[0]; a != "--other" {
		t.Fatalf("arg should be --other but got %q", a)
	}
}

func TestExecWithLogFile(t *testing.T) {
	ctx := context.Background()
	o := &Runc{}
	cmd := o.commandWithCustomLogFile(ctx, "/tmp/exec.log", "version")
	if got := strings.Join(cmd.Args[1:], " "); got != "--log /tmp/exec.log version" {
		t.Fatalf("expected args %q, got %q", "--log /tmp/exec.log version", got)
	}

	o = &Runc{Log: "/tmp/runc.log"}
	cmd = o.commandWithCustomLogFile(ctx, "/tmp/exec.log", "version")
	if got := strings.Join(cmd.Args[1:], " "); got != "--log /tmp/exec.log version" {
		t.Fatalf("expected args %q, got %q", "--log /tmp/exec.log version", got)
	}

	o = &Runc{Log: "/tmp/runc.log"}
	cmd = o.commandWithCustomLogFile(ctx, "", "version")
	if got := strings.Join(cmd.Args[1:], " "); got != "--log /tmp/runc.log version" {
		t.Fatalf("expected args %q, got %q", "--log /tmp/runc.log version", got)
	}

	o = &Runc{}
	cmd = o.commandWithCustomLogFile(ctx, "", "version")
	if got := strings.Join(cmd.Args[1:], " "); got != "version" {
		t.Fatalf("expected args %q, got %q", "version", got)
	}
}

func TestRuncFeatures(t *testing.T) {
	ctx := context.Background()
	if _, err := exec.LookPath(DefaultCommand); err != nil {
		t.Skipf("%q was not found in PATH", DefaultCommand)
	}
	runc := &Runc{}
	feat, err := runc.Features(ctx)
	if err != nil {
		t.Fatal(err)
	}
	var rroPresent bool
	for _, f := range feat.MountOptions {
		if f == "rro" {
			rroPresent = true
		}
	}
	if !rroPresent {
		t.Fatalf("\"rro\" was not found in feat.MountOptions (feat=%+v)", feat)
	}
}
