# -*- coding:utf-8 -*-
__author__ = 'ALIXie'

import logging
import shutil
import os
import re
import distutils.dir_util
import gw_file_system
import gw_data_center
import gw_apk_tool
import xml.etree.ElementTree as ET

ANDROID_NS = 'http://schemas.android.com/apk/res/android'
def script_init(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    gw_data_center.pack_small = False


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":
        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(workspace_sdk_dir, extract_dir, channel_sdk_info, new_game_channel_info, game_info):
    return

def script_last(workspace_sdk_dir, decompileDir, channel_sdk_info, new_game_channel_info, game_info):
    if channel_sdk_info['id'] == "512":
        s1 = os.path.join(decompileDir, "smali_classes5")
        smali_classes_new = create_mutil_smali(decompileDir)
        s3 = os.path.join(decompileDir, smali_classes_new)
        list_package = ["androidx"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

        s1 = os.path.join(decompileDir, "smali_classes6","com","netease")
        smali_classes_new = create_mutil_smali(decompileDir)
        s3 = os.path.join(decompileDir, smali_classes_new,"com","netease")
        list_package = ["dtws0mobilecfs","ntunisdk","pharos"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)

        move(decompileDir)
    else:
       move_smallsheep(decompileDir)

    if channel_sdk_info['id'] == "549":
        s1 = os.path.join(decompileDir, "smali_classes3")
        smali_classes_new = create_mutil_smali(decompileDir)
        s3 = os.path.join(decompileDir, smali_classes_new)
        list_package = ["androidx"]
        if not os.path.exists(s3):
            distutils.dir_util.mkpath(s3)
        move_package(s1, s3, list_package)
    return

def move_smallsheep(extract_dir):
    s1 = os.path.join(extract_dir, "smali_classes5","com/netease")
    smali_classes2_dir = gw_apk_tool.create_mutil_smali(extract_dir)
    s3 = os.path.join(smali_classes2_dir,"com/netease")
    list_package = ["android","cc","download","environment","httpdns","mobsec","neox","androidcrashhandler","ccrlsdk","downunifix","glide","loginapi","mpay"]
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
    gw_apk_tool.move_package(s1, s3, list_package)

def move(extract_dir):
    s1 = os.path.join(extract_dir, "smali_classes4")
    smali_classes2_dir = gw_apk_tool.create_mutil_smali(extract_dir)
    s3 = os.path.join(smali_classes2_dir)
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
    gw_apk_tool.move_package(s1, s3, ["androidx"])

    s1 = os.path.join(extract_dir, "smali_classes7","androidx")
    smali_classes2_dir = gw_apk_tool.create_mutil_smali(extract_dir)
    s3 = os.path.join(smali_classes2_dir,"androidx")
    list_package = ["activity","appcompat","asynclayoutinflater","core","customview","interpolator","lifecycle","localbroadcastmanager","annotation","arch","cardview","cursoradapter","documentfile","legacy","loader","media"]
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
    gw_apk_tool.move_package(s1, s3, list_package)

    s1 = os.path.join(extract_dir, "smali_classes8","com/netease/ntunisdk")
    smali_classes2_dir = gw_apk_tool.create_mutil_smali(extract_dir)
    s3 = os.path.join(smali_classes2_dir,"com/netease/ntunisdk")
    list_package = ["application","base","child","coolpad_sdk","extend","gamemode","langutil","ngshare","okio","picedit","atr","cclive","common","cutout","external","glide","modules","okhttp3","permissionkit","piclib"]
    if not os.path.exists(s3):
        distutils.dir_util.mkpath(s3)
    gw_apk_tool.move_package(s1, s3, list_package)


def add_checkSelfPermission(extract_dir):
    goal_file = os.path.join(extract_dir, 'smali/android/support/v4/content/ContextCompat.smali')
    add_method(goal_file)


def add_hjr_checkSelfPermission(extract_dir):
    goal_file = os.path.join(extract_dir, 'smali/android/support/haojieru/v4/content/ContextCompat.smali')
    add_method(goal_file)


def add_method(goal_file):
    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 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 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 = 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


if __name__ == "__main__":
    add_hjr_checkSelfPermission("C:\\Users\\Administrator\\Desktop\\dtws")
