#!/usr/bin/env python3

import os
import sys
import time
import subprocess
import tempfile
import argparse
try:
    from mako.template import Template
except:
    subprocess.check_output("pip3 install mako", shell=True)
    from mako.template import Template

BASEDIR = os.path.abspath(os.path.dirname(__file__) + "/..")

EMBLEM_HOSTS = [
        'themblem.com',
        'www.themblem.com',
        'dev.themblem.com',
        'emblem-dev.hond.cloud',
         ]

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--image", "-i", required=True)
    parser.add_argument("--db-host", "-d", required=True)
    parser.add_argument("--kubeconfig", required=True)
    parser.add_argument("--namespace","-n",  required=True)
    parser.add_argument("--emblem-env","-e",  required=True)
    return parser.parse_args()

def read_file(path):
    with open(path, 'r') as f:
        return f.read()


def render_template(template, **kwargs):
    t = Template(template)
    return t.render(**kwargs)

def wait_for_pod(kubeconfig, ns, ts):
    while True:
        time.sleep(1)
        cmd = ['kubectl', '--kubeconfig', kubeconfig, 'get', 'pod',
               '-n', ns,
               '-l', 'deploy-timestamp=' + ts]
        out = subprocess.check_output(cmd, encoding='utf-8')
        if 'Running' in out.split():
            return

def main():
    args = parse_args()
    tmpl_file = os.path.join(BASEDIR, "deploy/all.yaml.tmpl")
    template = read_file(tmpl_file)
    ts = str(time.time())
    t = render_template(template, image=args.image, db_host=args.db_host, emblem_env=args.emblem_env, hosts=EMBLEM_HOSTS,
                        deploy_timestamp=ts)
    f = tempfile.NamedTemporaryFile(suffix='.yaml', delete=False)
    f.write(t.encode())
    f.flush()
    kubeconfig = os.path.join(BASEDIR, "deploy/kubeconfig")
    cmd = ['kubectl', '--kubeconfig', args.kubeconfig, '-n', args.namespace,
           'apply', '-f', f.name]
    subprocess.check_output(cmd)
    wait_for_pod(args.kubeconfig, args.namespace, ts)

sys.exit(main())
