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

import yaml
import os
import logging
import distutils.dir_util
import gw_file_system

asserts_dex = "39285EFA.dex"


def script_first(SDK, decompileDir, channelSdkInfo, new_game_channel_info, gameInfo):
    logging.info("-----debug exec first func-----")
    # game_apk = os.path.join(decompileDir, "game.apk")
    game_apk = decompileDir + "/../game.apk"
    if os.path.exists(game_apk):
        gw_file_system.delete_apk_file_by_aapt(game_apk, "assets/" + asserts_dex)

    logging.info("-----script_first_debug-----")


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))
    # 360逆向渠道id
    if channel_sdk_info['id'] == "323":
        change_targetSdkVersion(extract_dir)
    if channel_sdk_info['id'] == "521":
        add_checkSelfPermission(extract_dir)

    dex = extract_dir + "../" + asserts_dex
    asserts = os.path.join(extract_dir, "assets/" + asserts_dex)
    if os.path.exists(asserts) and os.path.exists(os.path.join(dex)):
        distutils.dir_util.copy_tree(dex, asserts)


def change_targetSdkVersion(dir_path):
    yml_file = os.path.join(dir_path, 'apktool.yml')
    if not os.path.exists(yml_file):
        logging.info(yml_file + 'is not exist')
        return
    with open(yml_file, 'r') as f:
        d = yaml.load(f)
        print d
        sdkInfo = d.get('sdkInfo', {})
        sdkInfo.update({'targetSdkVersion': '22'})
        print d
    with open(yml_file, 'w') as fl:
        fl.write(yaml.dump(d))


def add_checkSelfPermission(extract_dir):
    goal_file = os.path.join(extract_dir, 'smali/android/support/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))


if __name__ == '__main__':
    change_targetSdkVersion('H:\\test')
