// Copyright 2018 PingCAP, Inc.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.

package utils

import (
	"fmt"
	"os"

	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

// GetClusterConfig returns a config object which uses the service account
// kubernetes gives to pods or specific kubeconfig. It's intended for clients that expect to be
// running inside a pod running on kubernetes or outside kubernetes. It will return an error if
// called from a process not running in a kubernetes environment and not specify kubeconfig.
func GetClusterConfig(kubeconfig string) (cfg *rest.Config, err error) {
	if kubeconfig != "" {
		cfg, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
	} else {
		cfg, err = rest.InClusterConfig()
	}
	if err != nil {
		return nil, err
	}
	return cfg, nil
}

// Return nil if file exists and is not a directory or not require validate file exists
func ValidateFileConfig(name string, config string, req bool) error {
	if !req {
		return nil
	}
	if name == "" {
		return fmt.Errorf("%s name must be specified", config)
	}
	info, err := os.Stat(name)
	if err != nil {
		return fmt.Errorf("%s: %s is invalid: %s", config, name, err)
	}
	if info.IsDir() {
		return fmt.Errorf("%s: %s must point to a file", config, name)
	}
	return nil
}

// Return nil if directory exists and is a directory
func ValidateDirectoryConfig(name string) error {
	info, err := os.Stat(name)
	if err != nil {
		return fmt.Errorf("directory: %s is invalid: %s", name, err)
	}
	if !info.IsDir() {
		return fmt.Errorf("directory: %s must point to a directory", name)
	}
	return nil
}
