#! /usr/bin/env python

##@namespace scripts.exhwrf_bufrprep
# Runs the hwrf.bufrprep.Bufrprep task to convert data tanks to bufr
# files for input to the hwrf.gsi tasks.

import os, sys, produtil.log, produtil.setup, produtil.cluster
from produtil.log import jlogger
import hwrf_wcoss,hwrf.gsi
from hwrf.gsi import unset_gsistatus, set_gsistatus, get_gsistatus
from produtil.ecflow import set_ecflow_event

def fail(msg):
    """!Logs an error message to the produtil.log.jlogger and exits with status 2.
    @param msg the string error message to log."""
    jlogger.error(msg)
    sys.exit(2)

def main():
    """!Runs the bufrprep task in hwrf_expt, a hwrf.bufrprep.Bufrprep.
    Creates the GSI status file, setting run_gsi_d0* variables to YES
    if the GSI is enabled for each domain."""
    import hwrf_expt
    hwrf_expt.init_module()
    conf=hwrf_expt.conf
    logger=conf.log('exhwrf_bufrprep')
    unset_gsistatus(conf,logger)

    if hwrf_expt.conf.getbool('config','run_gsi'):
        hwrf_expt.bufrprep.run()
    else:
        jlogger.info('GSI is disabled.  This job need not be run.')

    set_gsistatus(conf,logger)

    GsiD02=get_gsistatus(conf,'gsi_d02',logger)
    GsiD03=get_gsistatus(conf,'gsi_d03',logger)

    logger.info('Set/clear GSI status events: GsiD02=%s GsiD03=%s'%(
        repr(GsiD02),repr(GsiD03)))
    #c.alter(ecf_name,'change','event','GsiD02','set' if GsiD02 else 'clear')
    if GsiD02: set_ecflow_event('GsiD02',logger)
    #c.alter(ecf_name,'change','event','GsiD03','set' if GsiD03 else 'clear')
    if GsiD03: set_ecflow_event('GsiD03',logger)

if __name__=='__main__':
    try:
        produtil.setup.setup()
        main()
    except Exception as e:
        jlogger.critical('HWRF bufrprep is aborting: '+str(e),exc_info=True)
        sys.exit(2)