#!/usr/bin/env python3
import os,sys
from DMSCUtils.query import jobid,iscurrent
from Core.System import system
def usage(ec):
    print('%s [-h|--help] [-t|--trouble] [JOBDIR1] [[JOBDIR2] ...]'%os.path.basename(sys.argv[0]))
    print()
    print("Prints information about the slurm jobs (submitted with sb_dmscutils_submit) in the provided job dirs")
    print()
    print("Options:")
    print("  -h, --help    : Print this usage information.")
    print("  -t, --trouble : Silently ignore jobs which are not \"troubled\", meaning jobs no longer")
    print("                  present in the batch system which were not successful (exitcode.txt with \"0\").")
    sys.exit(0)

args=sys.argv[1:]
if '-h' in args or '--help' in args:
    usage(0)
opt_trouble_only = False
if '-t' in args:
    args.remove('-t')
    opt_trouble_only = True
if '--trouble' in args:
    args.remove('--trouble')
    opt_trouble_only = True

if not args:
    usage(1)
for a in args:
    j = jobid(a)
    if j==None:
        print('#'*80)
        print("WARNING: Not a job-dir: %s"%a)
        continue
    if opt_trouble_only:
        ecf=os.path.join(a,'exitcode.txt')
        if os.path.exists(ecf):
            ecf=open(ecf)
            ec=ecf.read().strip()
            ecf.close()
            if ec=='0':
                continue
        elif iscurrent(j):
            continue
    print('#'*80)
    print("# INFO about job %s (job ID %i):"%(os.path.basename(a),j))
    print('#')
    system("sacct -j %i --format JobID,JobName,Partition,State,ExitCode,Node|grep -v '^[0-9]*\\.'"%j)
