/*
Copyright 2020 The Kubernetes 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 ffs

import (
	"fmt"
	"os"
	"strings"
	"syscall"

	"github.com/container-storage-interface/spec/lib/go/csi"
	"github.com/kubernetes-csi/csi-lib-utils/protosanitizer"
	"github.com/pingcap/log"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"k8s.io/utils/mount"
)

func NewNodeServer(n *Driver, mounter mount.Interface) *NodeServer {
	return &NodeServer{
		Driver:  n,
		mounter: mounter,
	}
}

func NewIdentityServer(d *Driver) *IdentityServer {
	return &IdentityServer{
		Driver: d,
	}
}

func NewControllerServer(d *Driver) *ControllerServer {
	return &ControllerServer{
		Driver: d,
	}
}

func NewControllerServiceCapability(cap csi.ControllerServiceCapability_RPC_Type) *csi.ControllerServiceCapability {
	return &csi.ControllerServiceCapability{
		Type: &csi.ControllerServiceCapability_Rpc{
			Rpc: &csi.ControllerServiceCapability_RPC{
				Type: cap,
			},
		},
	}
}

func NewNodeServiceCapability(cap csi.NodeServiceCapability_RPC_Type) *csi.NodeServiceCapability {
	return &csi.NodeServiceCapability{
		Type: &csi.NodeServiceCapability_Rpc{
			Rpc: &csi.NodeServiceCapability_RPC{
				Type: cap,
			},
		},
	}
}

func ParseEndpoint(ep string) (string, string, error) {
	if strings.HasPrefix(strings.ToLower(ep), "unix://") || strings.HasPrefix(strings.ToLower(ep), "tcp://") {
		s := strings.SplitN(ep, "://", 2)
		if s[1] != "" {
			return s[0], s[1], nil
		}
	}
	return "", "", fmt.Errorf("Invalid endpoint: %v", ep)
}

const podSeparator = "/volumes/kubernetes.io~csi/"

func ParsePodPath(path string) (string, error) {
	if strings.Contains(path, podSeparator) {
		return path[:strings.Index(path, podSeparator)], nil
	}
	return "", fmt.Errorf("Invalid target path: %v", path)
}

func ExistPod(targets []string) bool {
	for _, target := range targets {
		podPath, err := ParsePodPath(target)
		if err != nil {
			continue
		}
		if _, err := os.Lstat(podPath); err != nil && os.IsNotExist(err) {
			log.S().Warnf("pod %s does not exist", podPath)
			continue
		}
		return true
	}
	return false
}

func ExistMountPoint(targets []string) bool {
	for _, targetPath := range targets {
		notMnt, err := mount.IsNotMountPoint(mount.New(""), targetPath)
		if !notMnt || err != nil && IsCorruptedMnt(err) {
			return true
		}
	}
	return false
}

func getLogLevel(method string) int32 {
	if method == "/csi.v1.Identity/Probe" ||
		method == "/csi.v1.Node/NodeGetCapabilities" ||
		method == "/csi.v1.Node/NodeGetVolumeStats" {
		return 8
	}
	return 2
}

func logGRPC(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
	log.S().Debugf("GRPC call: %s", info.FullMethod)
	log.S().Debugf("GRPC request: %s", protosanitizer.StripSecrets(req))

	resp, err := handler(ctx, req)
	if err != nil {
		log.S().Errorf("GRPC error: %v", err)
	} else {
		log.S().Debugf("GRPC response: %s", protosanitizer.StripSecrets(resp))
	}
	return resp, err
}

// IsCorruptedMnt return true if err is about corrupted mount point
func IsCorruptedMnt(err error) bool {
	if err == nil {
		return false
	}
	errMsg := err.Error()
	corrupted := mount.IsCorruptedMnt(err)
	if corrupted {
		return true
	}
	return strings.Contains(errMsg, syscall.ENOTCONN.Error()) ||
		strings.Contains(errMsg, syscall.ESTALE.Error()) ||
		strings.Contains(errMsg, syscall.EIO.Error()) ||
		strings.Contains(errMsg, syscall.EACCES.Error())
}

func IsNotMountPoint(target string) bool {
	if _, err := os.Lstat(target); err != nil && os.IsNotExist(err) {
		return true
	}
	var statfs syscall.Statfs_t
	if err := syscall.Statfs(target, &statfs); IsCorruptedMnt(err) {
		return false
	}
	notMnt, err := mount.IsNotMountPoint(mount.New(""), target)
	if !notMnt || IsCorruptedMnt(err) {
		return false
	}
	return true
}

func GetVolumeID(universe, zone, tenant, name string) string {
	idElements := make([]string, totalIDElements)
	idElements[idUniverse] = universe
	idElements[idZone] = zone
	idElements[idTenant] = tenant
	idElements[idName] = name
	return strings.Join(idElements, separator)
}

func ParseVolumeID(volumeId string) (universe, zone, tenant, name string, ok bool) {
	if !strings.Contains(volumeId, separator) {
		name = volumeId
		ok = true
		return
	}
	segments := strings.Split(volumeId, separator)
	if len(segments) == totalIDElements {
		universe = segments[idUniverse]
		zone = segments[idZone]
		tenant = segments[idTenant]
		name = segments[idName]
		ok = true
	}
	return
}
