#!/usr/bin/env python3
from __future__ import print_function
import os,sys,json
from collections import OrderedDict
import subprocess
import re

platform = sys.argv[1] if len(sys.argv) > 1 else None

assert platform in [None, "ios", "android"]

android = platform is None or platform == "android"
ios = platform is None or platform == "ios"

root = os.path.join(os.path.dirname(__file__), "..")
os.chdir(root)

package_file = os.path.join(root, "package.json")
package = json.load(open(package_file, "r", encoding="utf8"), object_pairs_hook=OrderedDict)

def error(message):
    print("ERROR: " + message)
    subprocess.check_call("""osascript -e 'display notification "%s" with title "<%= props.name %> Build"'""" % (message,), shell=True)

def pre_check():
    has_error = False

    if android and not os.getenv("APP_KEY"):
        error("Need to supply APP_KEY to unlock android keystore")
        has_error = True

    if subprocess.check_output(["git", "status", "--porcelain"]):
        error("Uncommited changes in git repository")
        has_error = True

    if has_error:
        sys.exit(1)

def bump_version():
    # Get the current version and increase patch by 1
    version = list(map(int, package["version"].split(".")))
    version[-1] += 1

    # Set the new version
    version_args = " ".join(map(str, version))
    subprocess.check_call("""python ./scripts/set-version.py %s""" % (version_args,), shell=True)

def run_tests():
    subprocess.check_call("yarn test", shell=True)

def build_ios():
    subprocess.check_call("cd ios && bundle exec fastlane beta", shell=True)

def build_android():
    subprocess.check_call("cd android && bundle exec fastlane alpha", shell=True)

def tag():
    subprocess.check_call(["git", "commit", "-am", "Release %s" % (package["version"],)])
    subprocess.check_call(["git", "tag", "release/%s" % (package["version"],)])
    subprocess.check_call(["git", "push"])
    subprocess.check_call(["git", "push", "--tags"])

try:
    print("-> Pre checks")
    pre_check()
    print("-> Run tests")
    run_tests()
    print("-> Bump version")
    bump_version()

    if android:
        print("-> Build android")
        build_android()

    if ios:
        print("-> Build IOS")
        build_ios()

    print("-> Tag")
    tag()
    print("ALL DONE")
    subprocess.check_call("""osascript -e 'display notification "Release complete" with title "<%= props.name %> Build"'""", shell=True)
except Exception as e:
    error("Build process failed")
    raise
