import subprocess
import json
import sys
import os


def build(ad_key, ad_ids, app_display_name,app_bundle_id,app_version,app_icon):
    
    cmd = """
    rm -rfv build
    mkdir build
    cp -rfv template/playbtest ./build/
    """

    subprocess.call(cmd, shell=True)
    # 创建编译目录复制模版到build目录

    print("--------------------")
    # 读取配置




    ### 复制icon

    cmd = f"""
    cp -fv {app_icon} ./build/playbtest/playbtest/Assets.xcassets/AppIcon.appiconset/1024x1024.png
    """
    subprocess.call(cmd, shell=True)

    ## 修改ad信息
    print("修改ad信息")
    code_path = './build/playbtest/playbtest/playB/bbbAdManager.swift' 
    with open(code_path, 'r') as f:
        code = f.read()
        code = code.replace("{adKey}", ad_key)
        code = code.replace("{allAdIds}", '"' + "\",\"".join(ad_ids) + '"')
    with open(code_path, 'w') as f:
        f.write(code)
        
    print("修改项目信息")
    prj_path = "./build/playbtest/playbtest.xcodeproj/project.pbxproj"
    with open(prj_path, 'r') as f:
        code = f.read()
        code = code.replace("{DisplayName}", app_display_name)
        code = code.replace("{BundleId}", app_bundle_id)
        code = code.replace("{Version}", app_version)
    with open(prj_path, 'w') as f:
        f.write(code)

    print("\n开始编译\n")
    cmd = """
    cd ./build/playbtest
    pod install --repo-update
    xcodebuild clean build -workspace playbtest.xcworkspace -configuration Release -scheme playbtest  -derivedDataPath "../Target"  -destination "platform=iOS,id=00008110-000815AE1179801E" 
    cd ../../
    """
    subprocess.call(cmd, shell=True)


    print("\n开始打包\n")

# codesign --entitlements ./template/Filza.entitlements -f -s "iPhone Distribution: Shumei Luo (T23C6PFSKY)" ./build/ipas/playbtest.app
#    find "./build/ipas/playbtest.app" -name "*.framework" -exec codesign -f -s "iPhone Distribution: Shumei Luo (T23C6PFSKY)" {} \;
#    find "./build/ipas/playbtest.app" -name "*.dylib" -exec codesign -f -s "iPhone Distribution: Shumei Luo (T23C6PFSKY)" {} \;
#    cp ./template/embedded.mobileprovision ./build/ipas/playbtest.app/embedded.mobileprovision 
#    codesign --entitlements ./template/Filza.entitlements -f -s "iPhone Distribution: Shumei Luo (T23C6PFSKY)" ./build/ipas/playbtest.app
    cmd = """
    mkdir ./build/ipas
    cp -rf ./build/Target/Build/Products/Release-iphoneos/playbtest.app ./build/ipas/
    
    find "./build/ipas/playbtest.app" -name "*.framework" -exec codesign -f -s "Apple Distribution: Haiyang Tang (544LFS79WN)" {} \;
    find "./build/ipas/playbtest.app" -name "*.dylib" -exec codesign -f -s "Apple Distribution: Haiyang Tang (544LFS79WN)" {} \;
    cp ./template/embedded.mobileprovision ./build/ipas/playbtest.app/embedded.mobileprovision 
    echo "codesign"
    codesign --entitlements ./template/Filza.entitlements -f -s "Apple Distribution: Haiyang Tang (544LFS79WN)" ./build/ipas/playbtest.app
    
    mkdir ./build/ipas/Payload
    mv ./build/ipas/playbtest.app ./build/ipas/Payload
    cd ./build/ipas
    zip -r playb-max.ipa Payload/
    """

    subprocess.call(cmd, shell=True)
    
    
    
if __name__ == '__main__':
    app_icon = "/Volumes/mfast/workspaces/projects/ios/lux-ipas/SpeedyColor/appicon.png"
    if len(sys.argv) < 2:
        ad_key = "Dd37BrtbLDlaeiDhxVzaDbsI67Mc1h5lAGIinzo4v2IbkpufdtVmT5Tag9O3aGexzkS4txEPigaEexktewANIk"
        ad_ids = ["7468dbe129ab2afe","7b61678bf643a84a","c6b7477edc2aff7e","28fd7967e71c9203"]
        app_display_name = "TimeCompass:Zones"
        app_bundle_id = "com.timeCompass.timeCompassZones"
        app_version = "1.1"
        
        build(ad_key, ad_ids, app_display_name, app_bundle_id, app_version, app_icon)
    else:
        json_path = sys.argv[1]
        with open(json_path, 'r') as f:
            config = json.loads(f.read())
        
        print(config)
        
        ad_key = config["sdk_key"]
        ad_ids = config["ad_ids"]
        app_display_name = config["app_name"]
        app_bundle_id = config["app_pkg_name"]
        app_version = config["app_ver"]
        app_icon_tmp:str = config["app_icon"]
        if not app_icon_tmp is None and app_icon_tmp.strip() != '':
            app_icon = os.path.join(os.path.dirname(json_path),  app_icon_tmp)
        
        build(ad_key, ad_ids, app_display_name, app_bundle_id, app_version, app_icon)
         
        
