package hostvolumemanager

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

	"github.com/hashicorp/go-hclog"
	"github.com/hashicorp/nomad/nomad/structs"
)

func TestVariantAttempts(t *testing.T) {
	log := hclog.NewNullLogger()

	pluginDir, err := os.MkdirTemp("", "plugin-dir")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(pluginDir)

	// create a legitimate plugin
	pluginFile := filepath.Join(pluginDir, "test_plugin.sh")
	os.WriteFile(pluginFile, []byte("#!/bin/sh\necho test"), 0755)

	// create a symlink to /bin/ls
	symlinkPath := filepath.Join(pluginDir, "symlink_plugin")
	os.Symlink("/bin/ls", symlinkPath)

	// Variant 1: path traversal payload (original CVE)
	_, err1 := NewHostVolumePluginExternal(log, pluginDir, "../../../../bin/ls", "/tmp/vols", "")
	fmt.Println("Variant 1 (traversal): err =", err1)

	// Variant 2: symlink payload
	_, err2 := NewHostVolumePluginExternal(log, pluginDir, "symlink_plugin", "/tmp/vols", "")
	fmt.Println("Variant 2 (symlink): err =", err2)

	// Variant 3: Register pluginID update check
	existing := &structs.HostVolume{NodeID: "abc", NodePool: "default", PluginID: "mkdir"}
	updated := &structs.HostVolume{NodeID: "abc", NodePool: "default", PluginID: "../../../../bin/ls"}
	err3 := updated.ValidateUpdate(existing)
	fmt.Println("Variant 3 (Register PluginID update): err =", err3)

	// Variant 4: Delete path inspection - does Delete call getPlugin?
	// Covered by code inspection; the test above covers the sink.

	blocked := 0
	if err1 != nil {
		blocked++
	}
	if err2 != nil {
		blocked++
	}

	fmt.Printf("RESULT: %d/2 direct traversal variants blocked\n", blocked)
	if err3 == nil {
		fmt.Println("RESULT: Register allows PluginID update (variant path exists)")
	} else {
		fmt.Println("RESULT: Register blocks PluginID update")
	}
}
