#! /usr/bin/env python

##@namespace scripts.exhwrf_ensda_pre
#Determines whether the ENSDA needs to be run for this cycle and
#writes the ENSDA flag file.

import sys, os
import produtil.setup, produtil.log
from produtil.log import jlogger
from hwrf.ensda import unset_ensdastatus

def main():
    """!Based on the configuration, write an ensda flag file that will
    either request, or not request, the ensemble da jobs to run."""
    import hwrf_expt
    hwrf_expt.init_module(make_ensemble_da=True)
    conf=hwrf_expt.conf
    logger=conf.log('exhwrf_ensda_pre')
    flag_file=conf.getstr('ensda_pre','tdr_flag_file')
    unset_ensdastatus(conf,flag_file,logger)
    flag_file=conf.getstr('ensda_pre','tdr_flag_file2')
    unset_ensdastatus(conf,flag_file,logger)
    run_ensemble_da=conf.getbool('config','run_ensemble_da',False)
    ensda_opt=conf.getint('config','ensda_opt',0)
    ensda_gfsinput_opt=conf.getbool('config','ensda_fallback',False)
    if not run_ensemble_da:
        jlogger.info('ENSDA is disabled for this configuration.  '
                     'This job need not be run.')
        hwrf_expt.ensda_pre.write_flag_file(False,False)
        return
    else:
        gfsinputexist=True
        if ensda_gfsinput_opt:
            gfsinputexist=hwrf_expt.ensda_pre_gfsinputcheck.run()
    
        if not gfsinputexist:
            hwrf_expt.ensda_pre.write_flag_file(False,False)
            return
        else:
            hwrf_expt.ensda_pre.run()

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