# -*-coding:utf-8-*-
import glob, os
import string
import random
import base64

class Garble:
    #api混淆
    def __rename_api(self,path,config):
        with open("%s/script/api_mapping"%config['root'], "r", encoding="utf-8") as f:
            lines = f.readlines()
            for line in lines:
                if "/sysdict/$1/$2" in line:
                    continue
                #去除无用字符
                line = line.replace("  "," ").replace("rewrite ^/","").replace("rewrite /","").replace("/(.+)","")\
                    .replace("/(.*)","").replace(" last;","").replace("\n","") \
                    .replace("/$1","").replace("/$2","").replace("/$3","").replace("/$4","").replace("/$5","")

                if "$ /" in line:
                    line = line.replace("$ /","*-*")
                else:
                    line = line.replace(" /","*-*")
                api_map = line.split("*-*")
                api_map[0].replace(" ","")
                api_map[1].replace(" ","")
                print(api_map[1]+ " -> " + api_map[0])

                with open(path, "r", encoding="utf-8") as api_file:
                    api_lines = api_file.readlines()
                #替换api
                with open(path, "w", encoding="utf-8") as f_w:
                    for api_l in api_lines:
                        old_line = "//" + api_l.replace("\n","//rewrited\n")

                        if "loanapp/{loanAppId}/bank" in api_l:
                            api_l = api_l.replace("loanapp/{loanAppId}/bank","loanapp/bank/{loanAppId}")
                        if "*Keep*" not in api_l and (api_map[1]+"/{" in api_l or api_map[1]+"\"" in api_l) and ( "@GET" in api_l or "@PUT" in api_l or "@POST" in api_l):
                            api_l = api_l.replace(api_map[1], api_map[0])
                            api_l = old_line + api_l.replace("\n","//rewrited\n")
                            print(api_map[1]+ " -> " + api_map[0])
                        f_w.write(api_l)
            print(path + "  done\n")
            return

    def api_garble(self,config):
        #java目录的路径
        for root, dirs, files in os.walk("%s/lib_base/src/main"%config['root']):
            directory = os.path.join(os.getcwd(), root)
            for file in files:
                #要检索的文件名
                if file.endswith("LoanApi.java") or file.endswith("UploadApi.java") or file.endswith("UserApi.java"):
                    # get the path of the java file
                    path = os.path.join(directory, file)
                    self.__rename_api(path,config)


    #字符串混淆
    def __string_grable(self,path):
        with open(path, "r") as f:
            lines = f.readlines()

        with open(path, "w") as f_w:
            for line in lines:
                if "<string" in line and "</string>\n" in line and "<!" not in line:
                    if "*keep*" not in line:
                        line = line.replace("</string>\n", "")
                        str_name = line.split(">")[0] + ">"
                        str_value = line.split(">")[1]
                        number=""
                        for i in range(0,random.randint(2,15)):
                            number += str(random.randint(0,9))
                        randStr = str(number) + "#-#"
                        grable_str = str(base64.b64encode((randStr + str_value).encode("utf-8")), "utf-8")
                        line = str_name + randStr + grable_str + "</string>\n"

                f_w.write(line)
            print("done\n")
        return

    def str_grable(self,config):
        for root, dirs, files in os.walk("%s/lib_base/src/main/res"% config['root']):
            directory = os.path.join(os.getcwd(), root)
            for file in files:
                if file.endswith("strings.xml"):
                    # get the path of the java file
                    path = os.path.join(directory, file)
                    self.__string_grable(path)

