#! /usr/bin/env python

import sys, os, logging, re, collections, io, getopt, itertools
from os.path import realpath, normpath, dirname

if len(sys.argv)!=3:
    print('Syntax: hmon.py YEAR STORMID')
    sys.exit(1)

#Get stormid and year from arguments
SID=sys.argv[2]
YEAR=sys.argv[1]
YEAR=int(YEAR)

# Get username:
USER=os.environ.get('USER')
CASE_ROOT=os.environ.get('CASE_ROOT')

# Set directories:
HOMEhmon=os.environ.get('HOMEhmon','')
if not HOMEhmon:
    os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

HOMEhwrf=HOMEhmon
if not HOMEhwrf:
    HOMEhwrf=os.path.join('/gpfs/hps/emc/hwrf/noscrub/Dan.Iredell/save/NOHWRF')

WORKSPACE=os.environ.get('WORKhmon','')
if not WORKSPACE:
    WORKSPACE=os.path.join("/gpfs/hps/ptmp/",USER,"/hmon") 
assert(WORKSPACE)

if not os.path.isdir(HOMEhwrf):
    print('%s: is not a directory.  Set $HOMEhwrf in environment.'%(HOMEhwrf,))
    sys.exit(1)
if not os.path.isdir(HOMEhmon):
    print('%s: is not a directory.  Set $HOMEhmon in environment.'%(HOMEhmon,))
    sys.exit(1)


# Load the HWRF scripts:

sys.path.append(os.path.join(HOMEhwrf,'ush'))

import produtil.sigsafety, produtil.fileop, produtil.run, produtil.atparse

import produtil.prog

from produtil.run import exe, runstr, run

from produtil.prog import shbackslash

# Initialize produtil  package without using produtil.setup():

logger=None
handler=None

# Install SIGTERM, SIGINT, etc. handlers.  Needed to handle batch job
# kills correctly.
produtil.sigsafety.install_handlers()
# Set up logging.  We customize things to look nice.
handler=logging.StreamHandler(sys.stderr)
handler.setFormatter(logging.Formatter(
        'hnmmb:%(levelname)s:%(asctime)s: %(message)s',
        '%Y%m%d.%H%M%S'))
logger=logging.getLogger()
logger.setLevel(logging.INFO)
logger.addHandler(handler)
   
########################################################################

# Parse vitals:

GENVIT=os.path.join(HOMEhwrf,'rocoto','hmon_generate_vitals.py')
cycledefs=runstr(exe(GENVIT)['-R','-n',SID,YEAR],logger)

########################################################################

outxml='./hmon-%s-%04d.xml'%(SID,YEAR)
assert(WORKSPACE)
with open(outxml,'wt') as outf:
    p=produtil.atparse.ATParser(logger=logger,stream=outf,varhash={
            'HOME':HOMEhmon,
            'SID':SID,
            'CYCLE_LIST':cycledefs,
            'WORKSPACE':WORKSPACE,
            })
    with open('./hmon_cpl.xml.in','rt') as inf:
        outf=p.parse_stream(inf,'./hmon_cpl.xml.in')

outdb='./hmon-%s-%04d.db'%(SID,YEAR)

ROCOTOhwrf=HOMEhwrf+'/rocoto'

##########################################################################
# Run rocotorun

cmd = exe('sh') [
    '--login', '-c', '. %s/hmon_pre_job.sh.inc ; rocotorun --verbose=5 -d %s -w %s'
    %( shbackslash(ROCOTOhwrf), shbackslash(outdb),
       shbackslash(outxml) ) ] .env(QUIET_PRE_JOB='YES',
                                    HOMEhwrf=HOMEhwrf,) \
                      < '/dev/null'

result=run(cmd,logger=logger)
if result:
    sys.exit(result)
    produtil.jlogger.critical('rocotorun failed')

#produtil.log.postmsg('Successfully ran rocotorun for %s.'%(outbase,))

####################################################################