# coding:utf8
import os
import logging
import re
import glob
import shutil
import distutils.dir_util
import gw_file_system
import xml.etree.ElementTree as ET

ANDROID_NS = 'http://schemas.android.com/apk/res/android'


def script(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    logging.info('game_pack_info: ' + str(channel_sdk_info))
    # 逆向渠道id
    if channel_sdk_info['id'] == "309":
        fixLifecycleMethod(extract_dir)
    return

def script_pre(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    sdk_id = channel_sdk_info['id']
    if sdk_id == "512" or sdk_id=="589" or  sdk_id=="597" or  sdk_id=="309":
        modify_manifest(extract_dir)
        game_mode_config = os.path.join(extract_dir, "res/xml-v22/game_mode_config.xml")
        os.remove(game_mode_config)
    return

def script_last(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    s1 = os.path.join(extract_dir, "smali_classes4", "com/netease")
    smali_classes2_dir = create_mutil_smali(extract_dir)
    s3 = os.path.join(smali_classes2_dir, "com", "netease")
    list_package = ["androidcrashhandler", "download", "godlikeshare", "pharos", "unisdk", "autotext", "environment", "onmyoji", "tryautotext2", "xyqa"]
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

    smali_classes2_dir = create_mutil_smali(extract_dir)
    s3 = os.path.join(smali_classes2_dir, "com", "netease")
    list_package = ["mpay", "neox", "ngpush", "ntunisdk"]
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

    if channel_sdk_info['id'] == "309":
        s1 = os.path.join(extract_dir, "smali_classes5", "com/netease")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir, "com", "netease")
        list_package = ["neox", "ngpush", "onmyoji"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
            move_package(s1, s3, list_package)

        s1 = os.path.join(extract_dir, "smali_classes5", "com/netease")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir, "com", "netease")
        list_package = ["ntunisdk", "onmyoji", "pharos"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
            move_package(s1, s3, list_package)

        s1 = os.path.join(extract_dir, "smali_classes5", "com/netease")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir, "com", "netease")
        list_package = ["androidcrashhandler", "autotext", "download", "environment", "godlikeshare", "htprotect"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
            move_package(s1, s3, list_package)

        s1 = os.path.join(extract_dir, "smali_classes5", "com/netease")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir, "com", "netease")
        list_package = ["a","amap","autonavi","bun","duoku","github","googlecode","huawei"," mcs","mp4parser","alipayx","asus","baidu","coremedia","example","google","heytap","JavaWebsocket","meizu"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
            move_package(s1, s3, list_package)

        s1 = os.path.join(extract_dir, "smali_classes5", "com")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir, "com")
        list_package = ["a","amap","autonavi","bun","duoku","github","googlecode","huawei"," mcs","mp4parser","alipayx","asus","baidu","coremedia","example","google","heytap","JavaWebsocket","meizu"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
            move_package(s1, s3, list_package)

        s1 = os.path.join(extract_dir, "smali_classes5", "com")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir, "com")
        list_package = ["netease","noah","random","samsung","sina","tax","tencent","utx","vivo","xiaomi","zui"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
            move_package(s1, s3, list_package)

        s1 = os.path.join(extract_dir, "smali_classes6", "com/netease")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir, "com", "netease")
        list_package = ["ntunisdk"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
            move_package(s1, s3, list_package)

        s1 = os.path.join(extract_dir, "smali_classes6", "com/netease")
        smali_classes2_dir = create_mutil_smali(extract_dir)
        s3 = os.path.join(smali_classes2_dir, "com", "netease")
        list_package = ["onmyoji","unisdk"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
            move_package(s1, s3, list_package)


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 = 5
    while True:
        tmp = gw_file_system.get_full_path(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


def intoFirstLine(target, repl, cont):
    # srcStr = "onBackPressed"
    # regexp = '.method (?:public|protected) +?'+target+"\([^.]+?\.locals +[0-9]{1,2}"
    regexp = '.method (?:public|protected) +?' + target + "\([^.]+?\.locals +([0-9]{1,2})"
    # print(regexp)
    reObj = re.compile(regexp)
    matchO = reObj.search(cont)
    if matchO:
        # print(matchO.group(0))
        methodHead = matchO.group(0)
        if matchO.group(1) == "0":
            methodHead = re.sub("locals +0", "locals 1", methodHead)

        repl = methodHead + r'\n\n    ' + repl + r'\n\n'
        cont = reObj.sub(repl, cont)
    else:
        # todo call .super method
        cont += r'.method protected ' + target + r'()V\n\n    .locals 0\n\n    ' + repl + r'\n\n    .end method\n'

    return cont


def fixLifecycleMethod(preDir):
    for tfile in glob.glob(preDir + "/" + "smali*/com/netease/onmyoji/Client.smali"):
        if os.path.isfile(tfile):
            with open(tfile, 'r+') as f:
                cont = f.read()
                changes = {
                    "onCreate": "invoke-static {p0}, Lcom/baidu/gamesdk/BDGameSDK;->setContext(Landroid/app/Activity;)V",
                }
                for k, v in changes.iteritems():
                    cont = intoFirstLine(k, v, cont)

                f.seek(0)
                f.write(cont)
                f.close()

def modify_manifest(decompileDir):
    ET.register_namespace('android', ANDROID_NS)
    xmlparse = os.path.join(decompileDir, 'AndroidManifest.xml')
    root_node = ET.parse(xmlparse)
    root = root_node.getroot()
    name = '{' + ANDROID_NS + '}name'
    authorities = '{' + ANDROID_NS + '}foregroundServiceType'
    package_name = root.attrib.get('package')
    if package_name == None:
        return
    providers = root.findall('./application/service')
    if providers != None:
        for provider in providers:
            providerName = provider.attrib.get(name)
            if 'com.netease.ntunisdk.CcMomentRecordingForegroundService' == providerName:
                # 使用try 主要是为了 防止此属性不在时，导致的错误，而程序终止
                try:
                    del provider.attrib[authorities]
                except:
                    ""

    root_node.write(xmlparse, 'utf-8')

if __name__ == '__main__':
    script("/tmp/ss", "/mnt/share/yanghuang/python_test/any_dir", {"id": "309"}, "", "")
    # hideSplash("/mnt/share/yanghuang/python_test/cr")
