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

class ActivityGarble:
    __config = {}
    used_names = []
    activity_mapping = {}

    #随机串
    def __gen_rand_str(self):
        rand_str = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=8))
        while rand_str in self.used_names:
            rand_str = ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=8))

        self.used_names.append(rand_str)
        return rand_str


    #替换文件内容
    def __process_file_content(self, path, file_name):
        # print("processing content: %s..."%path)
        with open(path, "rt") as fin:
            file_content = fin.read()
            # replace the file content based on mangle settings
            for (src, dst) in self.activity_mapping.items():
                #避免命名重复，确保要替换的部分前后没有合法的命名字符，如果有则还原
                file_content = file_content.replace(src, dst)
                before = re.findall(r'[0-9a-zA-Z]'+dst,file_content)
                if before is not None:
                    for name in before:
                        char = name.split(dst)[0]
                        file_content = file_content.replace(name, char + src)

                after = re.findall(r''+ "%s[0-9a-zA-Z]"% dst,file_content)
                if after is not None:
                    for name in after:
                        char = name.split(dst)[1]
                        file_content = file_content.replace(name,  src + char)

            ext = os.path.splitext(file_name)[1]
            if ext == '.java':
                comment = "// machine renamed: %s\n" % file_name
                file_content = "%s%s" % (comment, file_content)
            with open(path, "wt") as fout:
                fout.write(file_content)
        return

    #查找所有待混淆类 并重命名
    def __find_activities(self,path):
        for root, dirs, files in os.walk(path):
            directory = os.path.join(os.getcwd(), root)
            for file in files:
                is_activity = False
                for file_name in self.__config['activities']:
                    if file.endswith(file_name):
                        is_activity = True

                if is_activity:
                    name = os.path.splitext(file)[0]
                    if name not in self.activity_mapping.keys():
                        self.activity_mapping[name] = self.__gen_rand_str()
                        src = os.path.join(directory, file)
                        dst = os.path.join(directory, "%s.java" % self.activity_mapping[name])
                        os.rename(src, dst)

    #遍历混淆文件
    def __process_files(self,path):
        for root, dirs, files in os.walk(path):
            directory = os.path.join(os.getcwd(), root)
            for file in files:
                if file.endswith(".java") or file.endswith(".kt") or file.endswith(".xml"):
                    self.__process_file_content(os.path.join(directory, file),file)


    #四大组件混淆
    def activity_garble(self,config):
        self.__config = config
        #找到要混淆的java文件
        print("find activity...")
        for main_dir in config['lib_main']:
            self.__find_activities("%s/%s"% (config['root'],main_dir))
        
        #开始混淆
        print("start garble ...")
        for main_dir in config['lib_main']:
            self.__process_files("%s/%s"% (config['root'],main_dir))

        print("done")
