package docker

import (
	"bufio"
	"bytes"
	"errors"
	"io"
	"os"
	"regexp"
)

var (
	_containerdId string

	nameFeature = []byte("1:name")

	errNotMatch = errors.New("not match")

	containerdIDMatcher = regexp.MustCompile(`^[0-9a-zA-Z]+$`)
)

const (
	ContainerdIDLength = 64
)

func parseContainerID(r io.Reader) (id string, err error) {
	var (
		pos int
		p   []byte
	)
	br := bufio.NewReader(r)
	for {
		if p, _, err = br.ReadLine(); err != nil {
			break
		}
		if !bytes.HasPrefix(p, nameFeature) {
			continue
		}
		if len(p) > ContainerdIDLength {
			pos = len(p) - ContainerdIDLength
			if containerdIDMatcher.Match(p[pos:]) {
				return string(p[pos:]), nil
			}
		}
	}
	return "", errNotMatch
}

func SelfContainerID() (did string, err error) {
	if _containerdId != "" {
		return _containerdId, nil
	}
	var (
		fp *os.File
	)
	if fp, err = os.Open("/proc/self/cgroup"); err != nil {
		return
	}
	defer func() {
		_ = fp.Close()
	}()
	_containerdId, err = parseContainerID(fp)
	return _containerdId, err
}
