#!/bin/bash

function test_info(){
    local t_json=$1
cat > /tmp/mfr.py <<EOF
import sys, json;
import time;

def print_test(test, isOk):
    if isOk:
        print(f"    {test} \t\033[1;32m成功\033[0m")
    else:
        print(f"    {test} \t\033[1;31;40m失败\033[0m")

def load_time(t_time_str):
    t_time = time.strptime(t_time_str,"%Y-%m-%d %H:%M:%S")
    return int(time.mktime(t_time))

def load_json(t_json):
    with open(t_json, 'r') as f:
        data = json.load(f)
        if "tests" in data:
            b_test = None
            for t_test in data["tests"]:
                if b_test is None:
                    b_test = t_test
                else:
                    t1 = load_time(b_test["time"])
                    t2 = load_time(t_test["time"])
                    if t1 < t2:
                        b_test = t_test
            if b_test is not None:
                # print(f"测试时间：",b_test["time"])
                b_time=b_test["time"]
                if b_test["pass"]:
                    print(f"测试时间：{b_time}  \033[1;32m测试成功\033[0m")
                else:
                    print(f"测试时间：{b_time}  \033[1;31;40m测试失败\033[0m")
                if "execute" in b_test:
                    print("----------------------------------")
                    for t_test in b_test["execute"]:
                        print_test(t_test["name"], t_test["pass"])
                    print("----------------------------------")
                # if "pass" in b_test:
                #     print_test("测试", b_test["pass"])

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(f"json file")
        sys.exit(1)
    load_json(sys.argv[1])
EOF
    python3 /tmp/mfr.py ${t_json}
}

function load_log(){
    local log_dir=$1
    local t_year=$(ls ${log_dir} | sort -n -r | head -n 1)
    if [ -n "${t_year}" ];then
        local t_month=$(ls ${log_dir}"/"${t_year} | sort -n -r | head -n 1)
        if [ -n "${t_month}" ];then
            local t_day=$(ls ${log_dir}"/"${t_year}"/"${t_month} | sort -n -r | head -n 1)
            if [ -n "${t_day}" ];then
                for t_json in `find ${log_dir}"/"${t_year}"/"${t_month}"/"${t_day} -name *.json`
                do
                    test_info ${t_json}
                done  
            fi
        fi
    fi
}

function start(){
    local BASE_DIR="/var/log/mfr/"
    for product in `ls ${BASE_DIR}`
    do
        load_log "${BASE_DIR}${product}"
    done
}

start
