import file_utils
import config_utils
import sys
import os.path
import json

def packageChannel():
    if len(sys.argv) < 2:
        print('argument is missing')
        return 1

    channelConfig = sys.argv[1]

    jsonText = file_utils.readFile(channelConfig)
    config = json.loads(jsonText)

    print('*************config*****************')
    print(jsonText)
    print('************************************')

    # 检查配置
    if not checkConfig(config):
        return 1

    # 检查文件
    gameApk = config['package']
    if not os.path.exists(gameApk):
        print('%s not exists' % gameApk)
        return 1

    if supportSignV2(gameApk):
        packageChannelV2(gameApk, config)
        return 0
    else:
        print('apk not support Signature Scheme v2' % gameApk)
        return 1

def supportSignV2(gameApk):
    '''
    验证是否APK Signature Scheme v2
    '''
    apksigner = file_utils.getApksignerPath()
    ret = getJavaResult(apksigner, 'verify --verbose "%s"' % gameApk)

    if '(APK Signature Scheme v2): true' in ret:
        return True
    return False

def packageChannelV2(gameApk, config):
    print('add channel package ...')
    walle = file_utils.getWallePath()

    if not os.path.exists(config['outPath']):
        os.makedirs(config['outPath'])

    successCount = 0
    failureCount = 0
    channels = config['channel']
    for channel in channels:
        print('add channel package %s --> %s...' % (channel['agent'], channel['outName']))
        signedApk = os.path.join(config['outPath'], channel['outName'] + '.apk')
        ret = file_utils.execJarCmd(walle, 'put -c %s "%s" "%s"' % (channel['agent'], gameApk, signedApk))
        if ret:
            failureCount += 1
        else:
            successCount += 1

    print('success %d, failure %d' % (successCount, failureCount))

def checkConfig(config):
    if 'package' not in config:
        print('package not exists in config')
        return False

    if 'outPath' not in config:
        print('outPath not exists in config')
        return False

    if 'channel' not in config:
        print('channel not exists in config')
        return False

    return True

def getJavaResult(jar, cmd):
    return getCmdResult('java -jar "%s" %s' % (jar, cmd))

def getCmdResult(cmd):
    p = os.popen(cmd)
    content = p.read()
    return content

packageChannel()