#!/usr/bin/python3

import argparse
# import os
# import subprocess
import sys

from erimp import Erimp
from runer import Runer

desc = 'catch up on non-brems report'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-v', action='store_true', help='raise verbosity')
parser.add_argument('bapis', metavar='bnp', type=str, nargs='*',
                    help='bits and pieces arguments')
args = parser.parse_args()

e = Erimp(args.bapis, do_verbose=args.v)
do_verbose = args.v

repcode = e.given_repcode
if repcode is None:
    if do_verbose:
        print("I can't figure out what your report is.")
    sys.exit()

if 'bremse' in e.conf:
    if do_verbose:
        print("My erimp is bremsed.")
    sys.exit()

report = e.report[repcode]
if report.is_active():
    if do_verbose:
        print(f"{repcode} is active.")
    sys.exit()

train_run = e.dirs['bin'] + '/train -v ' + repcode
train_log = 'catchup_train_' + repcode

runer = Runer(e)
train_out = runer.run_with_lock(train_run, train_log)
if not bool(train_out):
    print('train failed', file=sys.stdout)
    sys.exit()

relis_run = e.dirs['bin'] + '/release -v -C ' + repcode
relis_log = 'catchup_relis_' + repcode
relis_out = runer.run_with_lock(relis_run, relis_log)
if do_verbose:
    print("I end with " + str(relis_out))
