package resourcebuilder

import (
	"fmt"

	corev1 "k8s.io/api/core/v1"
)

// updatePodSpecWithProxy mutates the input podspec with proxy env vars for all init containers and containers
// matching the container names.
func updatePodSpecWithProxy(podSpec *corev1.PodSpec, containerNames []string, httpProxy, httpsProxy, noProxy string) error {
	hasProxy := len(httpsProxy) > 0 || len(httpProxy) > 0 || len(noProxy) > 0
	if !hasProxy {
		return nil
	}

	for _, containerName := range containerNames {
		found := false
		for i := range podSpec.Containers {
			if podSpec.Containers[i].Name != containerName {
				continue
			}
			found = true

			podSpec.Containers[i].Env = append(podSpec.Containers[i].Env, corev1.EnvVar{Name: "HTTP_PROXY", Value: httpProxy})
			podSpec.Containers[i].Env = append(podSpec.Containers[i].Env, corev1.EnvVar{Name: "HTTPS_PROXY", Value: httpsProxy})
			podSpec.Containers[i].Env = append(podSpec.Containers[i].Env, corev1.EnvVar{Name: "NO_PROXY", Value: noProxy})
		}
		for i := range podSpec.InitContainers {
			if podSpec.InitContainers[i].Name != containerName {
				continue
			}
			found = true

			podSpec.InitContainers[i].Env = append(podSpec.InitContainers[i].Env, corev1.EnvVar{Name: "HTTP_PROXY", Value: httpProxy})
			podSpec.InitContainers[i].Env = append(podSpec.InitContainers[i].Env, corev1.EnvVar{Name: "HTTPS_PROXY", Value: httpsProxy})
			podSpec.InitContainers[i].Env = append(podSpec.InitContainers[i].Env, corev1.EnvVar{Name: "NO_PROXY", Value: noProxy})
		}

		if !found {
			return fmt.Errorf("requested injection for non-existent container: %q", containerName)
		}
	}

	return nil

}
