# coding:utf8

__author__ = 'dong'

import os
import logging
import xml.dom.minidom
import re
import shutil
import glob
from xml.etree.ElementTree import ElementTree, Element
import distutils.dir_util
import gw_data_center

from xml.etree import ElementTree as ET

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


def script_init(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    gw_data_center.pack_small = False
    return


def script_first(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    return


def script(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    sdk_id = channelSdkInfo['id']
    if sdk_id == "512":
        modify_manifest(decompileDir)
    return


def script_last(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    return


def create_mutil_smali(decompileDir):
    f_idx = 2
    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 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 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')


def del_android(decompileDir):
    android = os.path.join(decompileDir, 'smali/android/support/v4')
    if os.path.exists(android):
        shutil.rmtree(android)


def add_checkSelfPermission(extract_dir):
    goal_file = os.path.join(extract_dir, 'smali/android/support/haojieru/v4/content/ContextCompat.smali')
    if os.path.isfile(goal_file):
        with open(goal_file, 'r+') as f:
            lines = f.readlines()
            method = ['.method public static checkSelfPermission(Landroid/content/Context;Ljava/lang/String;)I\n',
                      '    .locals 2\n',
                      '    .param p0, "context"    # Landroid/content/Context;\n',
                      '         .annotation build Landroid/support/annotation/NonNull;\n',
                      '         .end annotation\n',
                      '    .end param\n',
                      '    .param p1, "permission"    # Ljava/lang/String;\n',
                      '         .annotation build Landroid/support/annotation/NonNull;\n',
                      '         .end annotation\n',
                      '    .end param\n',
                      '    if-eqz p1, :cond_0\n',
                      '    invoke-static {}, Landroid/os/Process;->myPid()I\n',
                      '    move-result v0\n',
                      '    invoke-static {}, Landroid/os/Process;->myUid()I\n',
                      '    move-result v1\n',
                      '    invoke-virtual {p0, p1, v0, v1}, Landroid/content/Context;->checkPermission(Ljava/lang/String;II)I\n',
                      '    move-result v0\n',
                      '    return v0\n',
                      '    :cond_0\n',
                      '    new-instance v0, Ljava/lang/IllegalArgumentException;\n',
                      '    const-string v1, "permission is null"\n',
                      '    invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V\n',
                      '    throw v0\n',
                      '.end method']
            for i in method:
                lines.append(i)
        with open(goal_file, 'w') as fl:
            fl.write(''.join(lines))


def del_okhttp_okio(extract_dir):
    okhttp3 = os.path.join(extract_dir, 'smali/okhttp3')
    if os.path.exists(okhttp3):
        shutil.rmtree(okhttp3)

    okio = os.path.join(extract_dir, 'smali/okio')
    if os.path.exists(okio):
        shutil.rmtree(okio)


def replace_emoj_textview(extract_dir):
    goal_file = os.path.join(extract_dir, 'res/layout/recycler_mail_list_item.xml')
    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 = 'com.elex.chatservice.view.emoj.EmojTextView'
            str = 'TextView'
            cont = cont.replace(change_str, str)
            logging.info('replace_str: ' + cont)
        with open(goal_file, 'w+') as tf:
            tf.write(cont)
    goal_file_2 = os.path.join(extract_dir, 'res/layout/msgitem_message_receive.xml')
    print(os.path.isfile(goal_file_2))
    if os.path.isfile(goal_file_2):
        logging.info('method_proceed: ' + 'goal_file')
        print(goal_file_2)
        with open(goal_file_2, 'r+') as f:
            cont = f.read()
            change_str = 'com.elex.chatservice.view.emoj.EmojTextView'
            str = 'TextView'
            cont = cont.replace(change_str, str)
            logging.info('replace_str: ' + cont)
        with open(goal_file_2, 'w+') as tf:
            tf.write(cont)
    goal_file_3 = os.path.join(extract_dir, 'res/layout/msgitem_message_send.xml')
    print(os.path.isfile(goal_file_3))
    if os.path.isfile(goal_file_3):
        logging.info('method_proceed: ' + 'goal_file')
        print(goal_file_3)
        with open(goal_file_3, 'r+') as f:
            cont = f.read()
            change_str = 'com.elex.chatservice.view.emoj.EmojTextView'
            str = 'TextView'
            cont = cont.replace(change_str, str)
            logging.info('replace_str: ' + cont)
        with open(goal_file_3, 'w+') as tf:
            tf.write(cont)


def replace_weboshare(decompileDir):
    src = os.path.join(decompileDir.replace('extract', ''), 'WeiBoShare.smali')
    print(src)
    logging.info('--------------src path:' + src)
    dest = os.path.join(decompileDir, 'smali_classes4/com/clash/of/share/WeiBoShare.smali')
    print(dest)
    logging.info('--------------dest path:' + dest)
    shutil.copyfile(src, dest)


def comment_logout_method(decompileDir):
    goal_file = os.path.join(decompileDir, 'smali/com/gameworks/sdk/standard/core/SDKKitCore.smali')
    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 = 'invoke-virtual {v0}, Lcom/game/sdk/HuosdkManager;->logout()V'
            str = '#invoke-virtual {v0}, Lcom/game/sdk/HuosdkManager;->logout()V'
            cont = cont.replace(change_str, str)
            logging.info('replace_str: ' + cont)
        with open(goal_file, 'w+') as tf:
            tf.write(cont)


def handle_public_xml(public_xml_path):
    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("wrap_content") > -1:
                continue
            new_lines.append(line)
        f.seek(0)
        f.truncate()
        f.writelines(new_lines)
    return


if __name__ == '__main__':
    # script("", "E:\\apk\\youhua\\LYJY360_12412_360逆向_1.23.00", "", "", "")
    modify_manifest("G:\\autopack2.0_kuaifa\\tool\\workspace\\mhlskp\\15377\\extract\\")
