/*
Copyright 2020 The Kubernetes Authors All rights reserved.

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

    http://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 cni

import (
	"bytes"
	_ "embed"
	"os/exec"
	"text/template"

	"github.com/pkg/errors"
	"k8s.io/klog/v2"
	"k8s.io/minikube/pkg/minikube/config"
)

// Generated by running `make update-cilium-version`
//
//go:embed cilium.yaml
var ciliumYaml string

var ciliumTmpl = template.Must(template.New("name").Parse(ciliumYaml))

// Cilium is the Cilium CNI manager
type Cilium struct {
	cc config.ClusterConfig
}

// String returns a string representation of this CNI
func (c Cilium) String() string {
	return "Cilium"
}

// CIDR returns the default CIDR used by this CNI
func (c Cilium) CIDR() string {
	return DefaultPodCIDR
}

// GenerateCiliumYAML generates the .yaml file
func GenerateCiliumYAML() ([]byte, error) {

	podCIDR := DefaultPodCIDR

	klog.Infof("Using pod CIDR: %s", podCIDR)

	opts := struct {
		PodSubnet string
	}{
		PodSubnet: podCIDR,
	}

	b := bytes.Buffer{}
	configTmpl := ciliumTmpl

	klog.Infof("cilium options: %+v", opts)
	if err := configTmpl.Execute(&b, opts); err != nil {
		return nil, err
	}
	klog.Infof("cilium config:\n%s\n", b.String())
	return b.Bytes(), nil
}

// Apply enables the CNI
func (c Cilium) Apply(r Runner) error {
	// see https://kubernetes.io/docs/tasks/administer-cluster/network-policy-provider/cilium-network-policy/
	if _, err := r.RunCmd(exec.Command("sudo", "/bin/bash", "-c", "grep 'bpffs /sys/fs/bpf' /proc/mounts || sudo mount bpffs -t bpf /sys/fs/bpf")); err != nil {
		return errors.Wrap(err, "bpf mount")
	}

	ciliumCfg, err := GenerateCiliumYAML()
	if err != nil {
		return errors.Wrap(err, "generating cilium cfg")
	}

	return applyManifest(c.cc, r, manifestAsset(ciliumCfg))
}
