/*
Copyright 2022 The Clusternet 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

    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 utils

import (
	"k8s.io/apimachinery/pkg/util/version"
	utilfeature "k8s.io/apiserver/pkg/util/feature"

	"github.com/clusternet/clusternet/pkg/features"
)

var (
	// KubeV1240Alpha4 indicates the version of Kubernetes v1.24.0-alpha.4
	KubeV1240Alpha4 = version.MustParseSemantic("v1.24.0-alpha.4")

	// KubeV1170Beta2 indicates the version of Kubernetes v1.17.0-beta.2
	KubeV1170Beta2 = version.MustParseSemantic("v1.17.0-beta.2")

	// KubeV1210Beta1 indicates the version of Kubernetes v1.21.0-beta.1
	KubeV1210Beta1 = version.MustParseSemantic("v1.21.0-beta.1")
)

// SATokenAutoGenerated is used to indicate whether secret-based service account token can be auto generated
func SATokenAutoGenerated(kubeServerVersion string) (bool, error) {
	parsedVersion, err := version.ParseSemantic(kubeServerVersion)
	if err != nil {
		return false, err
	}

	return parsedVersion.LessThan(KubeV1240Alpha4), nil
}

// EndpointSliceV1beta1Promoted is used to indicate whether EndpointSlice v1beta1 has been promoted
// Keep it for legacy use.
func EndpointSliceV1beta1Promoted(kubeServerVersion string) (bool, error) {
	parsedVersion, err := version.ParseSemantic(kubeServerVersion)
	if err != nil {
		return false, err
	}

	return parsedVersion.AtLeast(KubeV1170Beta2), nil
}

// MultiClusterServiceEnabled is used to indicate whether EndpointSlice v1 has been promoted
func MultiClusterServiceEnabled(kubeServerVersion string) (bool, error) {
	mcsEnabled := utilfeature.DefaultFeatureGate.Enabled(features.MultiClusterService)
	if !mcsEnabled {
		return false, nil
	}
	parsedVersion, err := version.ParseSemantic(kubeServerVersion)
	if err != nil {
		return false, err
	}

	return parsedVersion.AtLeast(KubeV1210Beta1), nil
}
