package targetpath

import (
	"errors"
	"regexp"
)

var (
	ErrInvalidTargetPath = errors.New("targetpath: parse: Invalid target path")
)

var (
	targetPathRegexp              = regexp.MustCompile("/pods/(?P<podid>[^/]+)/volumes/kubernetes.io~csi/(?P<volumeid>[^/]+)/mount$")
	targetPathRegexpPodIdIndex    = targetPathRegexp.SubexpIndex("podid")
	targetPathRegexpVolumeIdIndex = targetPathRegexp.SubexpIndex("volumeid")
)

// A TargetPath represents a parsed target path from Kubernetes.
type TargetPath struct {
	PodID    string
	VolumeID string
}

// Parse parses given target path from Kubernetes.
// Target paths are generated by Kubernetes for CSI drivers to mount their filesystem.
// They are in the form of "/var/lib/kubelet/pods/<pod-uuid>/volumes/kubernetes.io~csi/<volume-id>/mount".
func Parse(path string) (TargetPath, error) {
	matches := targetPathRegexp.FindStringSubmatch(path)
	if len(matches) < targetPathRegexpVolumeIdIndex {
		return TargetPath{}, ErrInvalidTargetPath
	}

	return TargetPath{
		VolumeID: matches[targetPathRegexpVolumeIdIndex],
		PodID:    matches[targetPathRegexpPodIdIndex],
	}, nil
}
