/*
Copyright © The ESO Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package addon

import (
	"fmt"
	"net/http"
	"os"
	"os/exec"

	. "github.com/onsi/ginkgo/v2"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/intstr"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
)

type HelmServer struct {
	ChartDir      string
	ChartRevision string

	config   *Config
	srv      *http.Server
	serveDir string
}

const serviceName = "e2e-helmserver"

func (s *HelmServer) Setup(config *Config) error {
	s.config = config
	var err error
	s.serveDir, err = os.MkdirTemp("", "e2e-helm")
	if err != nil {
		return err
	}

	// The chart's charts/ subchart tarballs are gitignored, so a fresh
	// checkout packages an empty charts/ and `helm package` fails with
	// "missing in charts/ directory". Build deps from the committed
	// Chart.lock first so this addon is self-contained: a suite that uses
	// only HelmServer (e.g. flux) has nothing else to populate charts/.
	cmd := exec.Command("helm", "dependency", "build", s.ChartDir)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("unable to build helm chart dependencies: %w %s", err, string(out))
	}

	// nolint:gosec
	cmd = exec.Command("helm", "package", s.ChartDir, "--version", s.ChartRevision)
	cmd.Dir = s.serveDir
	out, err = cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("unable to package helm chart: %w %s", err, string(out))
	}

	cmd = exec.Command("helm", "repo", "index", ".")
	cmd.Dir = s.serveDir
	out, err = cmd.CombinedOutput()
	if err != nil {
		return fmt.Errorf("unable to create helm index: %w %s", err, string(out))
	}

	svc := &v1.Service{
		ObjectMeta: metav1.ObjectMeta{
			Name:      serviceName,
			Namespace: "default",
		},
	}
	_, err = controllerutil.CreateOrUpdate(GinkgoT().Context(), s.config.CRClient, svc, func() error {
		svc.Spec = v1.ServiceSpec{
			Selector: map[string]string{
				// set via e2e/run.sh
				"app": "eso-e2e",
			},
			Ports: []v1.ServicePort{
				{
					Name:       "http",
					Port:       80,
					TargetPort: intstr.FromInt(3000),
				},
			}}
		return nil
	})

	return err
}

func (s *HelmServer) Install() error {
	fs := http.FileServer(http.Dir(s.serveDir))
	http.Handle("/", fs)
	s.srv = &http.Server{Addr: ":3000"}
	go func() {
		_ = s.srv.ListenAndServe()
	}()
	return nil
}

func (s *HelmServer) Logs() error {
	return nil
}

func (s *HelmServer) Uninstall() error {
	err := s.config.KubeClientSet.CoreV1().Services("default").Delete(GinkgoT().Context(), serviceName, metav1.DeleteOptions{})
	if err != nil {
		return err
	}
	return s.srv.Close()
}
