package vm

import (
	"fmt"
	"qvm/internal/config"
	"qvm/internal/virtiofsd"
	"strconv"
)

func buildQEMUCommand(cfg *config.Config, sshPort int, mounts []virtiofsd.Mount) []string {
	args := []string{
		"qemu-system-x86_64",
		"-enable-kvm",
	}

	memSize := cfg.VM.Memory
	args = append(args,
		"-object", fmt.Sprintf("memory-backend-memfd,id=mem,size=%s,share=on", memSize),
		"-numa", "node,memdev=mem",
	)

	args = append(args,
		"-smp", strconv.Itoa(cfg.VM.CPUs),
	)

	args = append(args,
		"-drive", fmt.Sprintf("if=virtio,file=%s,format=qcow2", config.Overlay),
	)

	args = append(args,
		"-nic", fmt.Sprintf("user,model=virtio-net-pci,hostfwd=tcp::%d-:22", sshPort),
	)

	args = append(args,
		"-serial", fmt.Sprintf("file:%s", config.SerialLog),
	)

	args = append(args,
		"-qmp", fmt.Sprintf("unix:%s,server,nowait", config.QMPSocket),
	)

	args = append(args,
		"-display", "none",
	)

	for _, mount := range mounts {
		args = append(args,
			"-chardev", fmt.Sprintf("socket,id=%s,path=%s", mount.Tag, mount.SocketPath),
			"-device", fmt.Sprintf("vhost-user-fs-pci,queue-size=1024,chardev=%s,tag=%s", mount.Tag, mount.Tag),
		)
	}

	return args
}
