/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package modifier

import (
	"dcu-container-toolkit/internal/config"
	"dcu-container-toolkit/internal/config/image"
	"dcu-container-toolkit/internal/discover"
	"dcu-container-toolkit/internal/logger"
	"dcu-container-toolkit/internal/lookup/root"
	"dcu-container-toolkit/internal/oci"
	"fmt"
)

// NewFeatureGatedModifier creates the modifiers for optional features.
// These include:
//
//	DTK_MOFED=enabled
//
// If not devices are selected, no changes are made.
func NewFeatureGatedModifier(logger logger.Interface, cfg *config.Config, image image.DTK, driver *root.Driver) (oci.SpecModifier, error) {
	if devices := image.VisibleDevicesFromEnvVar(); len(devices) == 0 {
		if devices = image.VdcuVisibleDevicesFromEnvVar(); len(devices) == 0 {
			logger.Infof("No modification required; no devices requested")
			return nil, nil
		}
	}

	var discoverers []discover.Discover

	if image.Getenv("DCU_MOFED") == "enabled" {
		d, err := discover.NewMOFEDDiscoverer(logger, driver.Root)
		if err != nil {
			return nil, fmt.Errorf("failed to construct discoverer for MOFED devices: %w", err)
		}
		discoverers = append(discoverers, d)
	}

	return NewModifierFromDiscoverer(logger, discover.Merge(discoverers...))
}
