import subprocess
import sys
import os
import json

def build_json(json_path):
    with open(json_path, 'r') as f:
        config = json.loads(f.read())
    t = config["type"]
    if t == "max":
        build_max(json_path)
    else:
        build_topon(json_path)

def build_max(json_path):
    build_path = "/Volumes/mfast/workspaces/projects/ios/build-ipa/max"
    build_script(build_path, json_path, "playb-max.ipa")


def build_topon(json_path):
    build_path = "/Volumes/mfast/workspaces/projects/ios/build-ipa/topon"
    build_script(build_path, json_path, "playb-topon.ipa") 
    
def build_script(build_path, json_path, ipa_name):
    cmd = """
    cd {0}
    python build.py {1}
    """.format(build_path, json_path)

    subprocess.call(cmd, shell=True)
    
    src_ipa = os.path.join(build_path,"build/ipas", ipa_name)
    target_path = os.path.dirname(json_path)
    cmd = """
    cp -fv {0} {1}
    """.format(src_ipa, target_path)
    
    subprocess.call(cmd, shell=True)
      

def build(base_path):
    print(base_path)
    for root, dirs, files in os.walk(base_path):
        for file in files:
            full_path = os.path.join(root, file)
            name = os.path.basename(full_path)
            if name == 'build.json':
                build_json(full_path)
    
if __name__ == '__main__':
    build(sys.argv[1])