package vmstart import ( "encoding/json" "errors" "fmt" "os" "path/filepath" "strings" "github.com/Nwflower/reims-go/internal/atomicfile" ) const vmNestedVirtConfigFile = ".reims-go-nested-virt.json" // VMNestedVirtConfig is persisted per VM in /.reims-go-nested-virt.json. The switch is // the VM's own; QEMU is told at each start (macosdriver.prepareNestedVirt). type VMNestedVirtConfig struct { Enabled bool `json:"enabled"` } // ReadVMNestedVirt loads /.reims-go-nested-virt.json. A VM without the file has the // switch off. A file that cannot be read is an error: the VM must not silently start without // a feature that was switched on. func ReadVMNestedVirt(vmDir string) (VMNestedVirtConfig, error) { if strings.TrimSpace(vmDir) == "" { return VMNestedVirtConfig{}, nil } path := filepath.Join(vmDir, vmNestedVirtConfigFile) data, err := os.ReadFile(path) if errors.Is(err, os.ErrNotExist) { return VMNestedVirtConfig{}, nil } if err != nil { return VMNestedVirtConfig{}, err } var cfg VMNestedVirtConfig if err := json.Unmarshal(data, &cfg); err != nil { return VMNestedVirtConfig{}, fmt.Errorf("%s: %w", path, err) } return cfg, nil } // SaveVMNestedVirt writes the switch; off removes the file. func SaveVMNestedVirt(vmDir string, cfg VMNestedVirtConfig) error { if strings.TrimSpace(vmDir) == "" { return errors.New("VM directory is empty") } dst := filepath.Join(vmDir, vmNestedVirtConfigFile) if !cfg.Enabled { if err := os.Remove(dst); err != nil && !errors.Is(err, os.ErrNotExist) { return err } return nil } return atomicfile.WriteJSON(dst, cfg, 0o600) }