#!/usr/bin/env python3

import os, sys, time, json
from globus_compute_sdk import Client, Executor, ShellFunction

from psik.zipstr import dir_to_str

if __name__=="__main__":
    argv = sys.argv

    with open("{{base}}/spec.json", "r", encoding="utf-8") as f:
        jobspec = json.dumps(json.load(f),separators=(',', ':'))
    with open("{{base}}/scripts/job", "r", encoding="utf-8") as f:
        script = f.read()
    jobndx = int(argv[1])

    if os.getenv("GLOBUS_COMPUTE_CLIENT_ID") is None:
        raise ValueError("GLOBUS_COMPUTE_CLIENT_ID env var must be defined")
    if os.getenv("GLOBUS_COMPUTE_CLIENT_SECRET") is None:
        raise ValueError("GLOBUS_COMPUTE_CLIENT_SECRET env var must be defined")

    # zip up the contents of the working dir.
    zstr = dir_to_str("{{job.directory}}")
    gclient = Client()
    with Executor( endpoint_id = "{{job.backend.queue_name}}"
                 , client = gclient
                 ) as gce:
            bf = ShellFunction(script % {
                    'jobndx': jobndx,
                    'jobspec': jobspec.replace("'", "''"),
                    'zstr': zstr
                    })
            print("Submitting job {{stamp}} idx %d"%jobndx, file=sys.stderr)
            future = gce.submit(bf)
            while future.task_id is None:
                time.sleep(1)
            print(gce.task_group_id.int)
            sys.stderr.flush()
            sys.stdout.flush()
            os._exit(0)
