#!/usr/bin/python3

import argparse
import os
import sys
import shutil
import subprocess

import filer
from erimp import Erimp
from infile import Infile
from ausfu import Ausfu
from rixer import Rixer

DESC = 'install nitpo file from sent file, part of ernad'
parser = argparse.ArgumentParser(description=DESC)
parser.add_argument('-v', action='store_true', help='raise verbosity')
parser.add_argument('-p', action='store_true', help='force publish')
parser.add_argument('-n', action='store_true', help='no send')
parser.add_argument('bapis', metavar='bnp', type=str, nargs='*',
                    help='bits and pieces arguments')
the_infile = Infile()
args = parser.parse_args()
do_publish = args.p
do_verbose = args.v
e = Erimp(args.bapis, do_verbose=args.v)
if 'nitpo_var_dir' not in e.conf:
    print("I need a nitpro_repis_fudi configuration", file=sys.stderr)
    sys.exit()
ausfu = Ausfu(e, do_verbose=args.v)
out_fudi = e.conf['nitpo_var_dir'] + '/repis'
if len(args.bapis) != 1:
    print("I need one input.")
    sys.exit()
in_fufi = args.bapis[0]
if not os.path.isfile(in_fufi):
    print(f"I can't see {in_fufi}", file=sys.stderr)
    sys.exit(1)
## the resulting ausfu_fufi does not have .gz, so it is added at the copying stage
## this is awkward
ausfu_doc = ausfu.by_fufi(in_fufi, show_email=True, do_write=False)
#if not os.path.isfile(ausfu_fufi):
#    print(f"{in_fufi} is not exported to {ausfu_fufi}", file=sys.stderr)
#    sys.exit(1)
in_bana = os.path.basename(in_fufi)
date = in_bana[0:10]
prior = in_bana[11:17]
repcode = os.path.basename(os.path.dirname(os.path.dirname(in_fufi)))
# # after change of order from prior_repcode to recode_prior, this could
# # prolly be simplifed
#if in_fufi.endswith('.amf.xml.gz'):
bana = repcode + '_' + prior + '.amf.xml.gz'
#elif in_fufi.endswith('.amf.xml'):
#    bana = repcode + '_' + prior + '.amf.xml'
#else:
#    raise Exception("I can't deal with " + in_fufi)
nitpo_fufi = out_fudi + '/' + date + '/' + bana
# # this is a general check for .gz
there_fufi = filer.is_there(nitpo_fufi)
if there_fufi is not None:
    nitpo_fufi = there_fufi
    if not do_publish:
        print(f"{there_fufi} is already there, use -p to continue.")
        sys.exit()
else:
    if the_infile.is_duplicate(nitpo_fufi):
        if not do_publish:
            print(f"{there_fufi} is a duplicate, use -p to continue.")
            sys.exit()
    filer.prepare(nitpo_fufi)
#    shutil.copy2(in_fufi, nitpo_fufi)
#    shutil.copy2(ausfu_fufi, nitpo_fufi + '.gz')

## add laubi
rixer = Rixer(e)
ausfu_doc = rixer.add_currency(ausfu_doc)
ausfu_doc.write(nitpo_fufi, pretty_print=True, compression=True)

if args.n:
    print(f"I wrote {nitpo_fufi}, and end")
    sys.exit()

# # run main script
home_dir = e.dirs['home']
base_run = ''
if 'PYTHONPATH' in os.environ:
    # run += 'export PYTHONPATH=' + os.environ['PYTHONPATH'] + '; '
    test_fufi = open('/tmp/test_python', 'w')
    test_fufi.write(os.environ['PYTHONPATH'])
    test_fufi.close()
base_run += 'export PYTHONPATH=/home/ernad/nitpo/python; '
impna = e.impna
for binf in ['orpis', 'repis']:
    run = base_run
    exec_fufi = home_dir + '/nitpo/bin/' + binf
    if not os.path.isfile(exec_fufi):
        print(f"I can't see {exec_fufi}")
        continue
    run += f"{exec_fufi} {nitpo_fufi}"
    log_dir = e.dirs['log'] + '/nitpo'
    log = log_dir + '/' + binf + '_' + date + '_' + prior + '_' + repcode
    err = '2> ' + log + '.err'
    out = '> ' + log + '.out'
    s = f"export HOME={home_dir}; "
    s += f" {run} {err} {out} "
    if do_verbose:
        print(s)
    subprocess.run(s, shell=True, check=False)
