#! /usr/bin/env python

##@namespace scripts.exhwrf_relocate
# Relocates, resizes and otherwise modifies the vortex from the
# parent model and prior HWRF cycle's forecast.  
#
# * $INIT_MODEL=GFS --- analysis time initialization, which does NOT
#   have to be from the GFS model.  
# * $INIT_MODEL=GDAS1 --- initialize from prior cycle of a global model,
#   which does NOT have to be from the GDAS model.  
# * $INIT_FHR=N --- for an integer N, the forecast hour of the prior
#   GDAS cycle.  This is generally a number from 3 to 9.
#
# @note Models other than GDAS and GFS can be used as initial, boundary
# and previous cycle forecast conditions by modifying the hwrf config
# files.  However, the $INIT_MODEL variable must still be set to GFS or
# GDAS.  For example, the GEFS-based HWRF ensemble runs a 20 member
# forecast ensemble using the GEFS 20 member forecast, but it still sets
# $INIT_MODEL=GFS when running its exhwrf_init scripts with GEFS data.

import os, sys, produtil.log, produtil.setup
from produtil.log import jlogger

def fail(msg):
    """!Log a message to produtil.log.jlogger and exit with status 0
    @param msg the error message"""
    jlogger.error(msg)
    sys.exit(2)

def main():
    """!Runs the hwrf.init.HWRFInit.run_relocate() for the selected initialization:

    * INIT_MODEL=GFS --- hwrf_expt.gfs_init.run_relocate()
    * INIT_MODEL=GDAS --- the run_relocate() is called for the appropriate
      member of hwrf_expt.fgat_init"""
    ENV=os.environ
    ompnum=ENV['OMP_NUM_THREADS']
    pureomp=ENV['PURE_OPENMP_THREADS']
    if ompnum != pureomp:
        os.environ['OMP_NUM_THREADS']=pureomp
    init_model=ENV['INIT_MODEL'].lower()
    init_fhr=int(ENV.get('INIT_FHR','0'))
    if init_model!='gfs' and init_model!='gdas1':
        fail('Aborting: init_model="%s" must be "gfs" or "gdas1"'%(init_model,))
    if init_model=='gdas1' and init_fhr<1:
        fail('Aborting: when init_model=gdas1, init_fhr must be >= 1 (init_fhr=%d)'%(init_fhr,))
    if init_model=='gfs': init_fhr=0
    
    import hwrf_expt
    hwrf_expt.init_module()

    if not hwrf_expt.conf.getbool('config','run_relocation'):
        jlogger.info('HWRF relocation is disabled; this job need not be run.  Exiting.')
        sys.exit(0)

    if init_model=='gfs':
        jlogger.info('HWRF relocation for GFS fhr starting')
        init=hwrf_expt.gfs_init.run_relocate()
        jlogger.info('HWRF relocation for GFS fhr completed')
    elif not hwrf_expt.conf.getbool('config','run_gsi'):
        jlogger.info('GSI is disabled.  This job need not be run.')
        sys.exit(0)
    else:
        init=None
        logger=hwrf_expt.fgat_init.log()
        logger.info('search for fgat hour %d'%(init_fhr,))
        for fhr,init in hwrf_expt.fgat_init.fhr_and_init():
            if abs(fhr-init_fhr)<0.01:
                logger.info('fhr %d is init_fhr %d'%(fhr,init_fhr))
                jlogger.info('HWRF relocation for GDAS1 fhr %d starting'%fhr)
                init.run_relocate()
                jlogger.info('HWRF relocation for GDAS1 fhr %d completed'%fhr)
                break
            else:
                logger.info('fhr %d is not init_fhr %d'%(fhr,init_fhr))
        assert(init is not None)

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