#!/usr/bin/python3

import argparse
import os
import sys
import shutil

from erimp import Erimp
from ishus import Ishus
from otria import Otria

import docing
desc = ''
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-v', action='store_true', help='raise verbosity')
parser.add_argument('-b', type=str, help='base_name')
parser.add_argument('-a', type=str, help='start')
parser.add_argument('-e', type=str, help='end')
parser.add_argument('-r', action='store_true', help='do release')
parser.add_argument('-n', type=str, help='end')
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)

if not args.b:
    if args.b is None and not args.r:
        print("I need a base name with -b")
        sys.exit()

if args.n is None:
    print("I need a number with -n")
    sys.exit()

end = ''
if args.e is not None:
    end = args.e

start = ' '
if args.r:
    start = "release "
if args.a is not None:
    start = args.a + ' '

otria = Otria(e)
ishus = Ishus(e)

issuedate = None
if args.r:
    #if e.given_issuedate is None:
    #    print("I need an issuedate")
    #    sys.exit
    issuedate = e.issuedates[0]

do_verbose = args.v
otria = Otria(e)
repcodes = otria.by_timely()

total = int(args.n)
batch = 0
texts = [''] * total

count = 1
for repcode in repcodes:
    report = e.report[repcode]
    if issuedate is not None and not report.audit_issuedate(issuedate):
        # # this should be added to a list of non-released reports
        if do_verbose:
            previous_issuedate = ishus.shift(issuedate, 1)
            print(f"{repcode} misses {previous_issuedate}")
        continue
    # # should be e.report[repcode]
    # report = Report(e, repcode)
    report = e.report[repcode]
    if not report.is_active():
        if do_verbose:
            print(f"{repcode} is not active")
        continue
    texts[count-1] += f"{start} {repcode} {end} \n"
    count += 1
    if count > total:
        count = 1

main = "#!/bin/bash\n\n"
count = 1
base = args.b
if args.r:
    base = 'release'
base = '/tmp/' + base
while count < total + 1:
    this = f"{base}_{count}"
    main += f"/usr/bin/chmod 755 {this}; "
    main += f"/usr/bin/nohup {this} 2> {this}.err > {this}.out &\n"
    count += 1

base_file = open(base, 'w')
base_file.write(main)
base_file.close()

count = 1
while count < total + 1:
    this = f"{base}_{count}"
    do_file = open(this, 'w')
    do_file.write(texts[count-1])
    do_file.close()
    count += 1
