/*
Copyright AppsCode Inc. and Contributors

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 identity

import (
	"context"
	"net"
	"strings"

	kmapi "kmodules.xyz/client-go/api/v1"
	clustermeta "kmodules.xyz/client-go/cluster"
	"kmodules.xyz/client-go/tools/clusterid"
	identityapi "kmodules.xyz/resource-metadata/apis/identity/v1alpha1"
	"kmodules.xyz/resource-metrics/api"

	"go.bytebuilders.dev/license-verifier/info"
	v "gomodules.xyz/x/version"
	core "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/client-go/discovery/cached/memory"
	"k8s.io/client-go/dynamic"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/restmapper"
	"sigs.k8s.io/yaml"
)

func GetSiteInfo(cfg *rest.Config, kc kubernetes.Interface, nodes []*core.Node, licenseID string) (*identityapi.SiteInfo, error) {
	si := identityapi.SiteInfo{
		TypeMeta: metav1.TypeMeta{
			APIVersion: identityapi.SchemeGroupVersion.String(),
			Kind:       "SiteInfo",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: SelfName,
		},
		Kubernetes: &identityapi.KubernetesInfo{},
	}

	if info.ProductName != "" || v.Version.Version != "" || licenseID != "" {
		si.Product = &identityapi.ProductInfo{}
		si.Product.LicenseID = licenseID
		si.Product.ProductOwnerName = info.ProductOwnerName
		si.Product.ProductOwnerUID = info.ProductOwnerUID
		si.Product.ProductName = info.ProductName
		si.Product.ProductUID = info.ProductUID
		si.Product.Version = identityapi.Version{
			Version:         v.Version.Version,
			VersionStrategy: v.Version.VersionStrategy,
			CommitHash:      v.Version.CommitHash,
			GitBranch:       v.Version.GitBranch,
			GitTag:          v.Version.GitTag,
			CommitTimestamp: v.Version.CommitTimestamp,
			GoVersion:       v.Version.GoVersion,
			Compiler:        v.Version.Compiler,
			Platform:        v.Version.Platform,
		}
	}

	cmeta, err := clusterid.ClusterMetadata(kc)
	if err != nil {
		return nil, err
	}
	si.Kubernetes.Cluster = cmeta
	si.Kubernetes.Version, err = kc.Discovery().ServerVersion()
	if err != nil {
		return nil, err
	}

	cert, err := clustermeta.APIServerCertificate(cfg)
	if err != nil {
		return nil, err
	} else {
		si.Kubernetes.ControlPlane = &identityapi.ControlPlaneInfo{
			NotBefore: metav1.NewTime(cert.NotBefore),
			NotAfter:  metav1.NewTime(cert.NotAfter),
			// DNSNames:       cert.DNSNames,
			EmailAddresses: cert.EmailAddresses,
			// IPAddresses:    cert.IPAddresses,
			// URIs:           cert.URIs,
		}

		dnsNames := sets.NewString(cert.DNSNames...)
		ips := sets.NewString()
		if len(cert.Subject.CommonName) > 0 {
			if ip := net.ParseIP(cert.Subject.CommonName); ip != nil {
				if !skipIP(ip) {
					ips.Insert(ip.String())
				}
			} else {
				dnsNames.Insert(cert.Subject.CommonName)
			}
		}

		for _, host := range dnsNames.UnsortedList() {
			if host == "kubernetes" ||
				host == "kubernetes.default" ||
				host == "kubernetes.default.svc" ||
				strings.HasSuffix(host, ".svc.cluster.local") ||
				host == "localhost" ||
				!strings.ContainsRune(host, '.') {
				dnsNames.Delete(host)
			}
		}
		si.Kubernetes.ControlPlane.DNSNames = dnsNames.List()

		for _, ip := range cert.IPAddresses {
			if !skipIP(ip) {
				ips.Insert(ip.String())
			}
		}
		si.Kubernetes.ControlPlane.IPAddresses = ips.List()

		uris := make([]string, 0, len(cert.URIs))
		for _, u := range cert.URIs {
			uris = append(uris, u.String())
		}
		si.Kubernetes.ControlPlane.URIs = uris
	}

	si.Kubernetes.Distributions = DetectDistributions(kc)

	scList, err := kc.StorageV1().StorageClasses().List(context.Background(), metav1.ListOptions{})
	scProvisioners := sets.NewString()
	if err == nil {
		for _, sc := range scList.Items {
			scProvisioners.Insert(sc.Provisioner)
		}
	}
	if scProvisioners.Len() > 0 {
		si.Kubernetes.StorageProvisioners = scProvisioners.List()
	}

	dc, err := dynamic.NewForConfig(cfg)
	if err != nil {
		return nil, err
	}
	if fc, err := dc.Resource(schema.GroupVersionResource{
		Group:    "cluster.open-cluster-management.io",
		Version:  "v1alpha1",
		Resource: "ClusterClaim",
	}).Get(context.Background(), kmapi.ClusterClaimKeyFeatures, metav1.GetOptions{}); err == nil {
		val, ok, err := unstructured.NestedString(fc.UnstructuredContent(), "spec", "value")
		if err == nil && ok && val != "" {
			var features kmapi.ClusterClaimFeatures
			if err := yaml.Unmarshal([]byte(val), &features); err == nil {
				si.Kubernetes.Features = &features
			}
		}
	}

	if len(nodes) == 0 {
		result, err := kc.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
		if err != nil {
			return nil, err
		}
		nodes = make([]*core.Node, len(result.Items))
		for i := range result.Items {
			nodes[i] = &result.Items[i]
		}
	}
	RefreshNodeStats(&si, nodes)

	return &si, nil
}

func RefreshNodeStats(si *identityapi.SiteInfo, nodes []*core.Node) {
	if len(nodes) == 0 {
		return
	}

	var total, cp, w identityapi.NodeStats
	for _, node := range nodes {
		total.Count++
		total.Capacity = api.AddResourceList(total.Capacity, node.Status.Capacity)
		total.Allocatable = api.AddResourceList(total.Allocatable, node.Status.Allocatable)

		if isControlPlaneNode(node) {
			cp.Count++
			cp.Capacity = api.AddResourceList(cp.Capacity, node.Status.Capacity)
			cp.Allocatable = api.AddResourceList(cp.Allocatable, node.Status.Allocatable)
		} else {
			w.Count++
			w.Capacity = api.AddResourceList(w.Capacity, node.Status.Capacity)
			w.Allocatable = api.AddResourceList(w.Allocatable, node.Status.Allocatable)
		}
	}

	si.Kubernetes.NodeStats.NodeStats = total
	if cp.Count > 0 {
		si.Kubernetes.NodeStats.ControlPlane = &cp
	}
	if w.Count > 0 {
		si.Kubernetes.NodeStats.Workers = &w
	}
}

func isControlPlaneNode(node *core.Node) bool {
	_, okCP := node.Labels["node-role.kubernetes.io/control-plane"]
	_, okMaster := node.Labels["node-role.kubernetes.io/master"]
	return okCP || okMaster
}

func skipIP(ip net.IP) bool {
	return ip.IsLoopback() ||
		ip.IsMulticast() ||
		ip.IsInterfaceLocalMulticast() ||
		ip.IsLinkLocalMulticast() ||
		ip.IsLinkLocalUnicast()
}

func DetectDistributions(kc kubernetes.Interface) []string {
	mapper := restmapper.NewDeferredDiscoveryRESTMapper(memory.NewMemCacheClient(kc.Discovery()))

	distros := sets.NewString()
	if clustermeta.IsRancherManaged(mapper) {
		distros.Insert(kmapi.ClusterManagerRancher.Name())
	}
	if clustermeta.IsOpenShiftManaged(mapper) {
		distros.Insert(kmapi.ClusterManagerOpenShift.Name())
	}
	return distros.List()
}
