#!/bin/python2

import sys
import argparse
import subprocess

def valid_category(s):
    cats = s.split()
    for c in cats:
        n = c.split('x')
        if len(n) != 2:
            msg = "%s is not a valid categor" % c
            raise argparse.ArgumentTypeError(msg)
        ress = n[1].split('-')
        if len(ress) != 3:
            msg = "%s is not a valid category" % c
            raise argparse.ArgumentTypeError(msg)
    return s

parser = argparse.ArgumentParser(description='Request exclusive use of nodes and no other jobs will be running on', 
                                 usage='exclsub [-h] -cat CATEGORY [shceduler_submit_options..] job_command')
parser.add_argument('-cat', '--category', required=True, type=valid_category, help='Node categories, e.g., "2x8-24-0 4x56-512-2" \
request two categories of nodes: the first category need 2 nodes, each node has 8 slots and 24GB memory; \
the second category need 4 nodes, each node has 56 cores, 512GB memory and 2 GPU. \
You could check available node categroy by running command "aip h c".')

args, other_args = parser.parse_known_args()
#print(args.category)
#print(other_args)

resreq = ""
cats = args.category.split()
for c in cats:
    n = c.split('x')
    nnode = int(n[0])
    ress = n[1].split('-')
    ncpu = int(ress[0])
    nmem = (int(ress[1])-1)*1024
    ngpu = int(ress[2])
    total = nnode*ncpu
    
    reqstr = "%d{select[maxmem=%d]span[ptile=%d]" % (total, nmem, ncpu)   
    if ngpu == 0:
        reqstr = "%s}" % reqstr
    else:
        rusage_gpu = float(ngpu)/total
        reqstr = "%srusage[gpu=%f]}" % (reqstr, rusage_gpu)
    if resreq == "":
        resreq = reqstr
    else:    
        resreq = resreq + " " + reqstr    
#print(resreq)

cmd = None
if "slurmjob" in other_args[-1] or "k8sjob" in other_args[-1]:
    cmd = "export CB_SLURM_SUBCLUSTER=1; csub -R \"%s\" %s" % (resreq, ' '.join(other_args))
else:
    cmd = "csub -R \"%s\" %s" % (resreq, ' '.join(other_args))
#print(cmd)

sp = subprocess.Popen(['sh', '-c', cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = sp.communicate()
if out:
    print(out)
if err:
    print(err)
