package configs

import (
	"fmt"
	"os"
	"strings"

	"github.com/HikariKnight/quickpassthrough/internal/logger"
	"github.com/HikariKnight/quickpassthrough/pkg/fileio"
)

// This function generates a modprobe file for /etc/modprobe.d/
func Set_Modprobe(gpu_IDs []string) {
	// Get the config
	config := GetConfig()

	// Read our current kernel arguments
	kernel_args := fileio.ReadFile(config.Path.CMDLINE)

	var vfio_pci_options []string
	vfio_pci_options = append(vfio_pci_options, strings.Join(gpu_IDs, ","))

	if strings.Contains(kernel_args, "vfio_pci.disable_vga=1") {
		// Write to logger
		logger.Printf("User has disabled vfio video output on host, adding disable_vga=1 to the optional hardcoded vfio_pci options\n")
		vfio_pci_options = append(vfio_pci_options, "disable_vga=1")
	}

	// Put our config file path into a string
	conffile := fmt.Sprintf("%s/vfio.conf", config.Path.MODPROBE)

	// If the file exists
	if fileio.FileExist(conffile) {
		// Delete the old file
		os.Remove(conffile)
	}

	content := fmt.Sprint(
		"## This is an autogenerated file that stubs your graphic card for use with vfio\n",
		"## This file should be placed inside /etc/modprobe.d/\n",
		"# Uncomment the line below to \"hardcode\" your graphic card to be bound to the vfio-pci driver.\n",
		"# In most cases this should not be neccessary, it will also prevent you from turning off vfio in the bootloader.\n",
		fmt.Sprintf(
			"#options vfio_pci ids=%s\n",
			strings.Join(vfio_pci_options, " "),
		),
		"\n",
		"# Make sure vfio_pci is loaded before these modules: nvidia, nouveau, amdgpu and radeon\n",
		"softdep nvidia pre: vfio vfio_pci\n",
		"softdep nouveau pre: vfio vfio_pci\n",
		"softdep amdgpu pre: vfio vfio_pci\n",
		"softdep radeon pre: vfio vfio_pci\n",
	)

	// Write to logger
	logger.Printf("Writing %s:\n%s", conffile, content)

	// Write the vfio.conf file to our modprobe config
	fileio.AppendContent(
		content,
		conffile,
	)

	// Make a backup of dracutConf if there is one there
	backupFile(strings.Replace(conffile, "config", "", 1))
}
