# coding:utf8

__author__ = '极无双'

import os
import logging
import xml.dom.minidom
import re
import shutil
import glob
import distutils.dir_util
import gw_apk_tool


def script_second(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    logging.info('script_second: ' + str(channel_sdk_info))
    # 逆向渠道id
    public_xml = os.path.join(extract_dir, "res/values/drawables.xml")
    handle_public_xml(public_xml, "APKTOOL")

    public_xml = os.path.join(extract_dir, "res/values/public.xml")
    handle_public_xml(public_xml, "APKTOOL")

    return


def script(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    logging.info('------------channelSdkInfo:' + str(channelSdkInfo))
    if channelSdkInfo['SDKName'] == 'reverseforkupai':
        del_coolcloud(decompileDir)
    if channelSdkInfo['id'] == '549':
        replace_life_method(decompileDir)

    sdk_id = channelSdkInfo['id']
    if sdk_id == "597":
        # s1 = os.path.join(decompileDir, "smali_classes2")
        # if os.path.exists(s1):
        #     smali_classes2_dir = create_mutil_smali(decompileDir)
        #     s3 = smali_classes2_dir
        #     if not os.path.exists(s3):
        #         distutils.dir_util.mkpath(s3)
        #     move_package(s1, s3, ["androidx"])

        extract_dir = decompileDir
        s1 = os.path.join(extract_dir, "smali_classes2", "androidx")
        smali_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_dir, "androidx")
        list_package = ["legacy", "lifecycle", "loader", "localbroadcastmanager", "media", "print", "slidingpanelayout",
                        "swiperefreshlayout", "vectordrawable", "versionedparcelable", "viewpager"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

        s1 = os.path.join(extract_dir, "smali_classes2", "androidx")
        smali_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_dir, "androidx")
        list_package = ["annotation", "appcompat", "arch", "asynclayoutinflater", "browser", "collection", "concurrent",
                        "coordinatorlayout", "core", "cursoradapter", "customview", "documentfile", "drawerlayout",
                        "fragment", "interpolator"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

        move_597(decompileDir)

def move_597(decompileDir):
    s1 = os.path.join(decompileDir, "smali_classes2/com")
    smali_classes_new = gw_apk_tool.create_mutil_smali(decompileDir)
    s3 = os.path.join(decompileDir, smali_classes_new, "com")
    list_package = ["qiniu","reyun","squareup","tencent","tools","unity","uwa","youme","RenderHeads","sina","taiyouxi","tendcloud","twobigears","unity3d","yingxiong"]
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
    gw_apk_tool.move_package(s1, s3, list_package)


def replace_life_method(extract_dir):
    goal_file = glob.glob(os.path.join(extract_dir, 'smali*/com/taiyouxi/a3k/MainActivity.smali'))[0]
    goal_file1 = glob.glob(os.path.join(extract_dir, 'smali*/com/yog/kothoth/utils/RequestParamUtil.smali'))[0]
    goal_file2 = glob.glob(os.path.join(extract_dir, 'smali*/com/yog/kothoth/data/JsonResult.smali'))[0]
    print(os.path.isfile(goal_file))
    if os.path.isfile(goal_file):
        logging.info('method_proceed: ' + 'goal_file')
        print(goal_file)
        with open(goal_file, 'r+') as f:
            cont = f.read()
            change_str = '.method protected onResume()V'
            str = '.method public onResume()V\n' \
                  'invoke-static {}, Lcom/kf/framework/SDKPluginWrapper;->onResume()V'
            cont = cont.replace(change_str, str)

            change_str_1 = '.method protected onPause()V'
            str_1 = '.method public onPause()V\n' \
                    'invoke-static {}, Lcom/kf/framework/SDKPluginWrapper;->onPause()V'
            cont = cont.replace(change_str_1, str_1)
            logging.info('replace_str: ' + cont)
        with open(goal_file, 'w+') as tf:
            tf.write(cont)
    if os.path.isfile(goal_file1):
        logging.info('method_proceed: ' + 'goal_file1')
        print(goal_file1)
        with open(goal_file1, 'r+') as f:
            cont = f.read()
            change_str = 'Lcom/hjr/gameplatform/aes/AESUtil'
            str = 'Lcom/kf/framework/util/AESUtil'
            cont = cont.replace(change_str, str)
            logging.info('replace_str: ' + cont)
        with open(goal_file1, 'w+') as tf:
            tf.write(cont)

    if os.path.isfile(goal_file2):
        logging.info('method_proceed: ' + 'goal_file2')
        print(goal_file2)
        with open(goal_file2, 'r+') as f:
            cont = f.read()
            change_str = 'Lcom/hjr/gameplatform/aes/AESUtil'
            str = 'Lcom/kf/framework/util/AESUtil'
            cont = cont.replace(change_str, str)
            logging.info('replace_str: ' + cont)
        with open(goal_file2, 'w+') as tf:
            tf.write(cont)


def is_reverse_coolcloud(file):
    with open(file, 'r+') as f:
        file_str = f.read()
        if 'KFSDK' in file_str:
            return True
        else:
            return False


def del_coolcloud(decompileDir):
    smali_files = glob.glob(os.path.join(decompileDir, 'smali*/com/coolcloud/'))
    if len(smali_files) > 1:
        iter_smali = iter(smali_files)
        while True:
            try:
                coolcloud_file_path = iter_smali.next()
                file = os.path.join(coolcloud_file_path, 'uac/android/api/Coolcloud.smali')
                if os.path.exists(file):
                    logging.info('Coolcloud exits in %s' % coolcloud_file_path)
                    if not is_reverse_coolcloud(file):
                        logging.info("delete coolcloud in %s" % coolcloud_file_path)
                        shutil.rmtree(coolcloud_file_path)
                    else:
                        pass
                else:
                    logging.info('Coolcloud not exits in %s' % coolcloud_file_path)
                    shutil.rmtree(coolcloud_file_path)

            except StopIteration:
                break


def handle_public_xml(public_xml_path, remove_node):
    if not os.path.exists(public_xml_path):
        logging.info('public_xml is null: ' + public_xml_path)
        return
    new_lines = []
    with open(public_xml_path, 'r+') as f:
        for line in f.readlines():
            # l = line.strip()
            if line.find(remove_node) > -1:
                continue
            new_lines.append(line)
        f.seek(0)
        f.truncate()
        f.writelines(new_lines)
    return


def move_package(s1, s3, list_package):
    for d in list_package:
        src = os.path.join(s1, d)
        if os.path.exists(src):
            dst = os.path.join(s3, d)
            distutils.dir_util.copy_tree(src, dst)
            distutils.dir_util.remove_tree(src)


def create_mutil_smali(decompileDir):
    f_idx = 2
    while True:
        tmp = os.path.join(decompileDir, 'smali_classes%d' % f_idx)
        tmp = tmp.replace('\\', '/')
        tmp = re.sub('/+', '/', tmp)
        if os.path.exists(tmp):
            f_idx += 1
        else:
            smali_classes2_dir = tmp
            break
    # endwhile
    os.mkdir(smali_classes2_dir)
    return smali_classes2_dir


if __name__ == '__main__':
    replace_life_method("D:\\work\\jws")
