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

class StringGarble:
     #字符串混淆
    def __string_garble(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)
        return

    #随机插入字符串
    def __insert_strings(self,path):
        with open(path, "r") as f:
            fileContent = f.read()

        strings = ""
        for i in range(0,random.randint(100,500)):
            strings += "%s\n"% ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=random.randint(5, 100)))
        with open(path, "w") as f_w:
            fileContent = fileContent.replace("</resources>","<string>%s</string>\n</resources>"% strings)
            f_w.write(fileContent)
        

    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)
                    print("process %s"% path)
                    self.__string_garble(path)
                    self.__insert_strings(path)
                    print("done")