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

class StringGarble:

    __used_names = []

    # 随机串(全小写加下划线，避免和activity混淆重复)
    def __gen_rand_str(self):
        result = ""
        while len(result) == 0 or result in self.__used_names:
            result = ''.join(random.sample(
                "abcdefghijklmnopqrstuvwxyz", random.randint(5, 15)))
        self.__used_names.append(result)
        return result

     #字符串混淆
    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_head = ""
        strings_foot = ""
        for i in range(0,random.randint(100,500)):
            key = self.__gen_rand_str()
            value = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=random.randint(5, 100)))
            if i % random.randint(1,10) == 0:
                strings_head += "<string name=\"%s\">%s</string>\n"% (key,value)
            else:
                strings_foot += "<string name=\"%s\">%s</string>\n"% (key,value)

        with open(path, "w") as f_w:
            fileContent = fileContent.replace("</resources>","%s\n</resources>"% strings_head)
            fileContent = fileContent.replace("<resources>","<resources>\n%s"% strings_foot)
            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")