import json
import os
import sys
import sqlite3 as sqlite

'''--------------------条件检索开始--------------------'''
#产线
def condition_production_line(production_line):
    p_line = ""
    #通过判断/etc/lsb-release
    cc = os.popen("cat /etc/lsb-release")
    cc_str = cc.read()
    if "openKylin" in cc_str:
        p_line = "openkylin"
    #通过判断/etc/kylin-build文件中是否有hwe字符串来区分是否是hwe产线
    if p_line == "":
        cc = os.popen("cat /etc/kylin-build")
        cc_str = cc.read()
        if "hwe" in cc_str:
            p_line = "hwe"
    #通过env | grep wayland来检索是否是wayland产线
    if p_line == "":
        cc = os.popen("env | grep wayland")
        cc_str = cc.read()
        if cc_str != "":
            p_line = "wayland"
    #都不是的话 才是xc产线
    if p_line == "":
        p_line = "xc"
    
    if production_line in p_line:
        return True
    else:
        return False
#系统buildid
def condition_buildid():
    return False
    pass
#系统环境
def condition_sys_env():
    return True
    pass
#架构
def condition_arch(arch):
    p_line = ""
    #通过判断/etc/kylin-build文件中是否有hwe字符串来区分是否是hwe产线
    cc = os.popen("arch")
    cc_str = cc.read()
    print("i am in condition_arch cc_str = ",cc_str,arch)
    if arch in cc_str:
        print("i am in condition_arch ,return True")
        return True
    else:
        print("i am in condition_arch ,return False")
        return False
#硬件--显卡
def condition_hardware_gpu(type):
    try:
        cc = os.popen("LANGUAGE=en_US LANG=en_US lshw -C display") #先检索普通机型，没有的话用华为的指令再检索
        cc_strs = cc.readlines()
        for cc_str in cc_strs:
            if "product" in cc_str:
                if type in cc_str:
                    return True
        cc = os.popen("LANGUAGE=en_US LANG=en_US gpuinfo")
        cc_strs = cc.readlines()
        for cc_str in cc_strs:
            if "type" in cc_str and "GPU" in cc_str:
                if type in cc_str:
                    return True
    except Exception as e:
        print("i am in condition_hardware_gpu,e = ",e)
        return False
    return False
#硬件--cpu
def condition_hardware_cpu(type):
    try:
        cc = os.popen("LANGUAGE=en_US LANG=en_US lscpu")
        cc_strs = cc.readlines()
        for cc_str in cc_strs:
            if "Model" in cc_str and "name" in cc_str:
                if type in cc_str:
                    return True
    except Exception as e:
        print("i am in condition_hardware_cpu,e = ",e)
        return False
    return False
#硬件
def condition_hardware(hardware):
    return_tf = True
    hardware_list = hardware.split("---")
    for hdware in hardware_list:
        hd = hdware.split(":")
        if hd[0] == "0x0003": #CPU
            return_tf = condition_hardware_cpu(hd[1])
            if return_tf == False:
                return False
        elif hd[0] == "0x0008": #显卡型号
            #华为机器通过gpuinfo指令抓取，其他机型通过lshw -C display抓取
            return_tf = condition_hardware_gpu(hd[1])
            if return_tf == False:
                return False
    return True
#问题组件--版本号
def condition_assembly_banben(deb_package):
    try:
        command = "dpkg -l | grep " + deb_package
        cc = os.popen(command)
        cc_strs = cc.readlines()
        for cc_str in cc_strs:
            deb_p = cc_str.split()[1]
            print("i am in condition_assembly_banben,deb_p =",deb_p.strip(),deb_package.strip())
            if deb_p.strip() == deb_package.strip(): 
                print("== cc_str.split()[2] = ",cc_str.split()[2])              
                return cc_str.split()[2]
    except Exception as e:
        print("i am in condition_assembly_banben,e = ",e)
        return ""
    return ""
#问题组件--版本号对比
def condition_assembly_banben_com(compare,now_banben,com_banben):
    try:
        command = "dpkg --compare-versions " + now_banben + " " + compare + " " + com_banben + " && echo 1 || echo 0"
        print("i am in condition_assembly_banben_com,command = ",command)
        cc = os.popen(command)
        cc_str = cc.read()
        if "1" in cc_str:
            return 1
        else:
            return 0
    except Exception as e:
        print("i am in condition_assembly_banben_com,e = ",e)
        return 0
#问题组件
def condition_assembly(assembly):
    #lt：less than 小于
    #le：less than or equal to 小于等于
    #eq：equal to 等于
    #ne：not equal to 不等于
    #ge：greater than or equal to 大于等于
    #gt：greater than 大于
    assembly_list = assembly.split("||")
    for assembly_str in assembly_list:
        if "<=" in assembly_str:
            print("i am in condition_assembly----- <=")
            assembly_table = assembly_str.split("<=")
            ret = condition_assembly_banben(assembly_table[0])
            if ret == "":
                return False
            ret1 = condition_assembly_banben_com("le",ret,assembly_table[1])
            if ret1 == 0:
                return False
            pass
        elif ">=" in assembly_str:
            print("i am in condition_assembly----- >=")
            assembly_table = assembly_str.split(">=")
            ret = condition_assembly_banben(assembly_table[0])
            if ret == "":
                return False
            ret1 = condition_assembly_banben_com("ge",ret,assembly_table[1])
            if ret1 == 0:
                return False
            pass
        elif "==" in assembly_str:
            print("i am in condition_assembly----- ==")
            assembly_table = assembly_str.split("==")
            ret = condition_assembly_banben(assembly_table[0])
            if ret == "":
                return False
            ret1 = condition_assembly_banben_com("eq",ret,assembly_table[1])
            if ret1 == 0:
                return False
            pass
        elif ">" in assembly_str:
            print("i am in condition_assembly----- >")
            assembly_table = assembly_str.split(">")
            ret = condition_assembly_banben(assembly_table[0])
            print("ret = ",ret)
            if ret == "":
                return False
            ret1 = condition_assembly_banben_com("gt",ret,assembly_table[1])
            if ret1 == 0:
                return False
            pass
        elif "<" in assembly_str:
            print("i am in condition_assembly----- <")
            assembly_table = assembly_str.split("<")
            ret = condition_assembly_banben(assembly_table[0])
            print("ret = ",ret)
            if ret == "":
                return False
            ret1 = condition_assembly_banben_com("lt",ret,assembly_table[1])
            if ret1 == 0:
                return False
            pass

    return True
    pass
#日志路径、#日志关键信息
def condition_log(log_path,key):
    key_table = key.split(",")
    with open(log_path,'r') as f:
        while True:
            try:   
                line = f.readline()
                #print("-----------------line = ",line)
                if line=="":
                    break     

                line_temp = line.split()
                #关键字核对
                if len(key_table) > 0:
                    for item in key_table:
                        if item.lower() in line.lower().replace(" ",""):
                            return True
                            break

            except Exception as e:
                print("i am in start_findlog_button_clicked e = :",e)
                continue
    return False

#def condition_log_key():
#    pass
#磁盘检测工具,检测结果
def condition_auto_check(shell_data,shell_result):
    print("shell_data = ",shell_data)
    #strs = shell_data.split("\n")
    report_result_name = "/tmp/kydoctor_shell.sh"
    result_fd = open(report_result_name,"w")
    result_fd.write(shell_data)
    result_fd.close()
    
    cc = os.system("bash /tmp/kydoctor_shell.sh")
    #cc_strs = cc.read()
    print("cc_strs = ",cc)
    if cc != 0:
        return True
    else:
        return False

    return True
    pass
#检测结果
#def condition_check_result():
#    return True
#    pass

'''--------------------条件检索结束--------------------'''
#字符串增加一位
def add_char_to_string(string1):
    string_list = list(string1)
    string_list.insert(2,0)
    new_string = ''.join(str(x) for x in string_list)
    return new_string

def checkitemfromsql(error_cls):
    #print("int = ",int(error_cls))
    #print("hex(int) = ",hex(int(error_cls)))
    #print("str(hex(int())) = ",str(hex(int(error_cls))))
    hexerror_cls_str = str(hex(int(error_cls)))
    print("hexerror_cls_str = ",hexerror_cls_str)
    if len(hexerror_cls_str) == 17:
        hexerror_cls_str = add_char_to_string(hexerror_cls_str)
    print("hexerror_cls_str = ",hexerror_cls_str)
    #提取hexerror_cls_str固定位数，用于检索数据库
    select_str = hexerror_cls_str[:8]
    
    db_dir = "/opt/kydoctor/common/db/" #数据库路径
    #db_dir = "./"
    db_dir_path = db_dir+"solution.db"
    if not os.path.exists(db_dir_path):
        print("solution.db not exist!")
        return -1

    con = sqlite.connect(db_dir_path)
    try:
        my_dict = {}
        with con:
            cur = con.cursor()
            cur.execute("select * from errordata where error_cls=:error_cls",{"error_cls":select_str})
            rows = cur.fetchall()
            print("i am in checkitem,len(rows) = ",len(rows))
            
            test_all = len(rows)
            test_right = 0
            test_error = 0

            my_dict = {}
            for row in rows:
                print("i am in checkitem row = ",row)
                temp_condition_all = True
                if row[3] == "" and row[4] == "" and row[5] == "" and row[6] == "" and row[7] == "" \
                and row[8] == "" and row[9] == "" and row[10] == "" and row[11] == "" and  row[12] == "":
                    temp_condition_all = False
                #产线
                if row[3] != "" and temp_condition_all == True:
                    if condition_production_line(row[3]) != True:
                        temp_condition_all = False
                #系统buildid
                if row[4] != "" and temp_condition_all == True:
                    if condition_buildid() != True:
                        print("i am in buildid,condition_buildid() != True")
                        temp_condition_all = False
                #系统环境
                if row[5] != "" and temp_condition_all == True:
                    if condition_sys_env() != True:
                        temp_condition_all = False
                #架构
                if row[6] != "" and temp_condition_all == True:
                    print("i am in arch,row[6] = ",row[6])
                    if condition_arch(row[6]) != True:
                        print("i am in arch,row[6] != True")
                        temp_condition_all = False
                #硬件
                if row[7] != "" and temp_condition_all == True:
                    if condition_hardware(row[7]) != True:
                        temp_condition_all = False
                #问题组件
                if row[8] != "" and temp_condition_all == True:
                    if condition_assembly(row[8]) != True:
                        temp_condition_all = False
                #日志路径、#日志关键信息
                if row[9] != "" and row[10] != "" and temp_condition_all == True:
                    if condition_log(row[9],row[10]) != True:
                        temp_condition_all = False
                #自动检测工具--检测结果
                if row[11] != "" and temp_condition_all == True:
                    if condition_auto_check(row[11],row[12]) != True:
                        temp_condition_all = False
                #检测结果
                #if row[12] != "" and temp_condition_all == True:
                #    if condition_check_result() != True:
                #        temp_condition_all = False
                
                if temp_condition_all == True:
                    test_right = test_right + 1
                    error_dict = {}
                    error_dict["ErrorCode"] = row[2]
                    error_dict["Describe"] = row[13]
                    error_dict["Name"] = row[14]
                    if "Details" not in my_dict:
                        my_dict["Details"] = [error_dict]
                    else:
                        my_dict["Details"].append(error_dict)
            test_error = test_all - test_right
            overview_str = "检测了 " + str(test_all) + " 项，"+str(test_right) +" 项错误，"+ str(test_error)+" 项正确"
            my_dict["Overview"] = overview_str
            print("i am in checkitem,my_dict = ",my_dict)

            json_table_str = json.dumps(my_dict)

            #开始往临时文件中写数据
            report_result_name = "/tmp/kydoctor"
            result_fd = open(report_result_name,"w")
            result_fd.write(json_table_str)
            result_fd.close()
    except Exception as e:
        print("in checkitem,error :",e)
        return -1
    return 0
def checkitemfromtxt(error_cls):
    db_dir_path = "/tmp/kydoctor_c_sql"
    if not os.path.exists(db_dir_path):
        print("checkitemfromtxt，/tmp/kydoctor_c_sql not exist!")
        return -1

    try:
        my_dict = {}
        test_all = 0
        test_right = 0
        test_error = 0
        file1 = open(db_dir_path)
        text = file1.read()
        text_line = text.split("****")
        for texts in text_line:
        #while True:
            #text = file1.readline()
            if len(texts) == 0:
                break
            test_all = test_all + 1
            row = texts.split("+++")
            #for row in rows:
            print("i am in checkitem row = ",row)
            temp_condition_all = True
            if row[3] == "" and row[4] == "" and row[5] == "" and row[6] == "" and row[7] == "" \
            and row[8] == "" and row[9] == "" and row[10] == "" and row[11] == "" and  row[12] == "":
                temp_condition_all = False
            #产线
            if row[3] != "" and temp_condition_all == True:
                if condition_production_line(row[3]) != True:
                    temp_condition_all = False
            #系统buildid
            if row[4] != "" and temp_condition_all == True:
                if condition_buildid() != True:
                    print("i am in buildid,condition_buildid() != True")
                    temp_condition_all = False
            #系统环境
            if row[5] != "" and temp_condition_all == True:
                if condition_sys_env() != True:
                    temp_condition_all = False
            #架构
            if row[6] != "" and temp_condition_all == True:
                print("i am in arch,row[6] = ",row[6])
                if condition_arch(row[6]) != True:
                    print("i am in arch,row[6] != True")
                    temp_condition_all = False
            #硬件
            if row[7] != "" and temp_condition_all == True:
                if condition_hardware(row[7]) != True:
                    temp_condition_all = False
            #问题组件
            if row[8] != "" and temp_condition_all == True:
                if condition_assembly(row[8]) != True:
                    temp_condition_all = False
            #日志路径、#日志关键信息
            if row[9] != "" and row[10] != "" and temp_condition_all == True:
                if condition_log(row[9],row[10]) != True:
                    temp_condition_all = False
            #自动检测工具--检测结果
            if row[11] != "" and temp_condition_all == True:
                if condition_auto_check(row[11],row[12]) != True:
                    temp_condition_all = False
            #检测结果
            #if row[12] != "" and temp_condition_all == True:
            #    if condition_check_result() != True:
            #        temp_condition_all = False
            
            if temp_condition_all == True:
                test_right = test_right + 1
                error_dict = {}
                error_dict["ErrorCode"] = row[2]
                error_dict["Describe"] = row[13]
                error_dict["Name"] = row[14]
                if "Details" not in my_dict:
                    my_dict["Details"] = [error_dict]
                else:
                    my_dict["Details"].append(error_dict)
        test_error = test_all - test_right
        overview_str = "检测了 " + str(test_all) + " 项，"+str(test_right) +" 项错误，"+ str(test_error)+" 项正确"
        my_dict["Overview"] = overview_str
        print("i am in checkitem,my_dict = ",my_dict)

        json_table_str = json.dumps(my_dict)

        #开始往临时文件中写数据
        report_result_name = "/tmp/kydoctor"
        result_fd = open(report_result_name,"w")
        result_fd.write(json_table_str)
        result_fd.close()
        file1.close()
    except Exception as e:
        if os.path.exists(db_dir_path):
            os.remove(db_dir_path)
        print("in checkitem,error :",e)
        return -1
    if os.path.exists(db_dir_path):
        os.remove(db_dir_path)
    return 0
if __name__ == "__main__":
    #ret = checkitemfromsql(sys.argv[1])
    ret = checkitemfromtxt(sys.argv[1])
    if ret == -1:
        exit(-1)
    else:
        exit(0)

