from calculate.utils.files import grep_file
import os

class SystemType:
    """
    Тип контейнера текущей системы
    """
    Uml = "uml"
    VServer = "vserver"
    OpenVZ = "openvz"
    LXC = "lxc"
    Docker = "docker"
    Xen0 = "xen0"
    XenU = "xenU"
    Rkt = "rkt"
    SystemdNSpawn = "systemd-nspawn"
    NotDetected = ""

    @classmethod
    def detect_container(cls):
        if grep_file("/proc/cpuinfo", "UML"):
            return cls.Uml
        elif grep_file("/proc/self/status",
                "(s_context|VxID):\s*[1-9]"):
            return cls.VServer
        elif (os.path.exists("/proc/vz/veinfo")
              and not os.path.exists("/proc/vz/version")):
            return cls.OpenVZ
        elif grep_file("/proc/self/status", "envID:\s*[1-9]"):
            return cls.OpenVZ
        elif grep_file("/proc/1/environ", "container=lxc"):
            return cls.LXC
        elif grep_file("/proc/1/environ", "container=rkt"):
            return cls.Rkt
        elif grep_file("/proc/1/environ", "container=systemd-nspawn"):
            return cls.SystemdNSpawn
        elif os.path.exists("/.dockerenv"):
            return cls.Docker
        elif grep_file("/proc/1/environ", "container=docker"):
            return cls.Docker
        return cls.NotDetected

    @classmethod
    def detect_vm(cls):
        if os.path.exists("/proc/xen"):
            if grep_file("/proc/xen/capabilities", "control_d"):
                return cls.Xen0
            return cls.XenU
        return cls.NotDetected

    @classmethod
    def detect(cls):
        return cls.detect_container() or cls.detect_vm()
