#!/usr/bin/env python3

import subprocess, argparse, sys, re
import time as t

parser = argparse.ArgumentParser()
parser.add_argument('-t', '--timeout', '-timeout', help="Timeout waitinf for SB to finish", type=float, default=120)
parser.add_argument('-s', '--sbid', '-sbid', help="Don't submit SB, just look for passed SBID")
parser.add_argument('parset', help="Parset for Medusa Frequency Setup")

SCHEDBLOCK = "schedblock"


args = parser.parse_args()


if args.sbid is None:
    cmd = [SCHEDBLOCK, "create", "-a", "Reconfig",  "-o",  "VLBI", "-p",  args.parset,  "-t",  "MedusaConfig"]
    out = subprocess.run(cmd, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if out.stderr != "":
        print("Error: schedblock create returned '{}'".format(out.sterr))
        sys.exit(1)

    m = re.search('The new SchedulingBlock has the id: (\d+)', out.stdout)
    if m is None:
        print("Error: Did not understand schedblock outout '{}'".format(out.stdout.strip()))
        sys.exit(1)

    print(out.stdout, end='')
    sbid  = m.group(1)

    cmd = [SCHEDBLOCK, "schedule", sbid]

    out = subprocess.run(cmd, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    if out.stderr != "":
        print("Error: schedblock schedule returned '{}'".format(out.sterr))
        sys.exit(1)

    print(out.stdout, end='')

else:
    sbid = args.sbid

print("DEBUG: Looking for SBID={}".format(sbid))
    
t0 = t.time()

cmd = [SCHEDBLOCK, "list"]

reSBID = re.compile('(\d+)\s+Reconfig\s+(\S+)\s+MedusaConfig\s+\d+\s+VLBI')

while t.time()-t0 < args.timeout:
    
    out = subprocess.run(cmd, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if out.stderr != "":
        print("Error: schedblock list returned '{}'".format(out.sterr))
        sys.exit(1)

    print(out.stdout, end='')

    matched = False
    for line in out.stdout.splitlines(False):
        m = reSBID.match(line)
        if m is not None:
            matched = True
            if m.group(1)==sbid and m.group(2)=='OBSERVED':
                print("Complete")
                sys.exit(0)
            if m.group(1)==sbid and m.group(2)=='ERRORED':
                print("\n\n ERROR:  {} has Errored!!!!\n\n".format(sbid))
                sys.exit(0)
    if not matched:
        print("Error: Did not understand output")
        sys.exit(1)
    t.sleep(2)

# Only get here on timeout

print("Error: Timeout before SBID observed")
