#!/usr/bin/env python3

import os
import tempfile
import subprocess
import argparse

BASE_DIR = os.path.abspath(os.path.dirname(__file__) + '/..')

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("action", help="CI action: build, push")
    return parser.parse_args()

NAME = subprocess.check_output('git rev-parse --short HEAD', shell=True, encoding='utf-8').strip()
IMG_TAG = "registry.cn-shenzhen.aliyuncs.com/euphon-private/emblem-detection:" + NAME

print(IMG_TAG)

def do_test():
    subprocess.check_call("docker run --rm --network=host %s ./tests/run.py" % IMG_TAG, shell=True)

def do_build():
    subprocess.check_call("docker build --network=host -t %s ." % IMG_TAG, shell=True)

def do_push():
    subprocess.check_call("docker push %s" % IMG_TAG, shell=True)

def do_deploy(env=""):
    kubeconfig = os.path.join(BASE_DIR, 'deploy/kubeconfig.' + env)
    src = os.path.join(BASE_DIR, 'deploy/detection.yaml')
    tf = tempfile.NamedTemporaryFile(mode='w')
    with open(src, 'r') as f:
        tmpl = f.read()
        tf.write(tmpl.format(image=IMG_TAG))
        tf.flush()
    cmd = ['kubectl', '--kubeconfig', kubeconfig, 'apply', '-f', tf.name]
    subprocess.check_call(cmd)
def main():
    args = parse_args()
    if args.action == "build":
        return do_build()
    elif args.action == "test":
        return do_test()
    elif args.action == "push":
        return do_push()
    elif args.action == "deploy-prod":
        return do_deploy('prod')
    elif args.action == "deploy-dev":
        return do_deploy('dev')
    raise Exception("Unrecognized command")

main()
