import hashlib
import logging
import os
import socket
import subprocess
import uuid
from website import settings

def get_cpu_id():
    p = subprocess.Popen(["dmidecode -t 4 | grep ID | tail -1"],
                         shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    data = p.stdout
    lines = []
    while True:
        line = str(data.readline(), encoding="utf-8")
        if line == '\n':
            break
        if line:
            d = dict([line.strip().split(': ')])
            lines.append(d)
        else:
            break
    return lines


def get_system_uuid():
    p = subprocess.Popen(["dmidecode -s system-uuid"],
                         shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    data = p.stdout
    lines = []
    while True:
        line = str(data.readline(), encoding="utf-8")
        if line == '\n':
            break
        if line:
            lines.append(line)
        else:
            break
    print("system uuid {}".format(lines))

    return lines


def get_system_manufacture():
    p = subprocess.Popen(["dmidecode -s processor-manufacturer | tail -1"],
                         shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    data = p.stdout
    lines = []
    while True:
        line = str(data.readline(), encoding="utf-8")
        if line == '\n':
            break
        if line:
            lines.append(line)
        else:
            break

    return lines


def get_board_manufacturer():
    p = subprocess.Popen(["dmidecode -s baseboard-manufacturer"],
                         shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    data = p.stdout
    lines = []
    while True:
        line = str(data.readline(), encoding="utf-8")
        if line == '\n':
            break
        if line:
            lines.append(line)
        else:
            break

    return lines


def get_board_serial_number():
    p = subprocess.Popen(["dmidecode -s baseboard-serial-number"],
                         shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    data = p.stdout
    lines = []
    while True:
        line = str(data.readline(), encoding="utf-8")
        if line == '\n':
            break
        if line:
            lines.append(line)
        else:
            break

    return lines


def get_board_serialnumber():
    p = subprocess.Popen(["dmidecode -t 2 | grep Serial"],
                         shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    data = p.stdout
    lines = []
    while True:
        line = str(data.readline(), encoding="utf-8")
        if line == '\n':
            break
        if line:
            d = dict([line.strip().split(': ')])
            lines.append(d)
        else:
            break
    return lines


def get_idntify_code_v2():
    cpuid = get_cpu_id()
    system_uuid = get_system_uuid()
    system_manufacture = get_system_manufacture()
    board_manufacturer = get_board_manufacturer()
    board_serial_number = get_board_serial_number()
    s = ""

    if cpuid:
        s += cpuid[0]["ID"]
        print("cpuid: ", cpuid[0]["ID"])
    if system_uuid:
        print(system_uuid)
        s += system_uuid[0].strip()
    if system_manufacture:
        print(system_manufacture)
        s += system_manufacture[0].strip()
    if board_manufacturer:
        print(board_manufacturer)
        s += board_manufacturer[0].strip()
    if board_serial_number:
        print(board_serial_number)
        s += board_serial_number[0].strip()

    s += settings.system_salt
    # system_salt = "5bVQmI0ATh+QITf75WgVchT6TPN1DEOasSmrtMcTsPQ="
    # s += system_salt
    code = hashlib.sha256(s.encode("utf8")).hexdigest()
    return code


def get_identify_code():
    mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
    mac_addr = ":".join([mac[e:e + 2] for e in range(0, 11, 2)])

    host_name = socket.getfqdn(socket.gethostname())
    cpu_ids = get_cpu_id()
    serialnumbers = get_board_serialnumber()

    s = ""
    if mac_addr:
        s += mac_addr
    if host_name:
        s += host_name
    if cpu_ids:
        for cpu in cpu_ids:
            s += cpu["ID"]
    if serialnumbers:
        for number in serialnumbers:
            s += number["Serial Number"]
    logging.info(s)

    code = hashlib.new('md5', s.encode("utf8")).hexdigest()
    return code


def get_docker_container_id():
    # 获取当前 Docker 容器的 ID
    cmd = "cat /proc/self/cgroup"
    output = os.popen(cmd)
    rests = output.readlines()
    container_message = rests[-1]
    if not container_message:
        container_id = "abc"
    else:
        container_id = container_message.strip().split("docker/")[-1]
    return container_id


if __name__ == "__main__":
    print(get_idntify_code_v2())