#!/bin/ksh
# $Id: ins_job 1644 2012-01-31 16:31:30Z jgipsl $
#---------------------------------------------------------------------
#- Installation of jobs according to an environment
#---------------------------------------------------------------------
function ins_job_Usage
{
print - "
ins_job installs the jobs in the directories
which contain a file config.card

ins_job must be launched on the host
on which the job will be submitted

Usage :
  ${b_n} [-h] [-v]

Options :
  -h   : help
  -v   : verbose mode
"
}
function ins_job_Warning
{
   print - "\n############### WARNING ###############";
   print - "File ${n_f} already exists\nin directory ${j}";
   print - "You must delete this file to update !";
}
#-
#     dirname     and      basename
#-
d_n=$(dirname ${0}); b_n=$(basename ${0});
#-
# Retrieving and validation of the options
#-
x_v='silencious';
while getopts :hv V
  do
   case $V in
    (h)  ins_job_Usage; exit 0;;
    (v)  x_v='verbose';;
    (:)  echo ${b_n}" : -"${OPTARG}" option : missing value" 1>&2;
         exit 2;;
    (\?) echo ${b_n}" : -"${OPTARG}" option : not supported" 1>&2;
         exit 2;;
    esac
  done
shift $(($OPTIND-1));
#-
# Define working files
#-
F_MOD=$(cd ${d_n}'/..';/bin/pwd;)
# [[ ${F_MOD##*/} != 'modipsl' ]] && \
#  { print - "directory 'modipsl' unreachable"; exit 3; }
W_W=${d_n}'/../libIGCM'
[[ ! -d ${W_W} ]] && { print - "${W_W} unreachable"; exit 3; }
libIGCM=$(cd ${W_W};/bin/pwd;)
F_JOB=${libIGCM}'/AA_job';
[[ ! -f ${F_JOB} ]] && { print - "${F_JOB} unreachable"; exit 3; }
F_RCI=${libIGCM}'/run.card.init';
[[ ! -f ${F_RCI} ]] && { print - "${F_RCI} unreachable"; exit 3; }
#-
# Host Name
#-
x_t=$(${d_n}/w_i_h) 2>/dev/null;
{ [[ ${?} != 0 ]] && \
   { print - "\nw_i_h or uname unreachable\n" 1>&2; exit 1; }; } || \
  [[ ${x_t} = "Unknown" ]] && \
   { print - "\nLocal_Host not supported\n" 1>&2; exit 1; };
#-
W_W=$(sed -n -e "s/^#-Q-  *\([^ ]*\).*$/\1/p" ${F_JOB} | \
       sort -u | sed -e "/${x_t}/!d");
[[ '\?'"${W_W}" != '\?'${x_t} ]] && \
  {
   print - "\nHost  "${x_t}"  not supported" 1>&2;
   print - "'default' will be used" 1>&2;
   x_t='default'
  }
#-
[[ ${x_v} = 'verbose' ]] && \
 {
  print - "";
  print - '--- Host        : '${x_t};
  print - '--- modipsl     : '${F_MOD};
  print - '--- libIGCM     : '${libIGCM};
  print - '--- basic job   : '${F_JOB};
  print - '--- basic card  : '${F_RCI};
 }
#-
print - "\nInstallation of jobs for '${x_t}'";
#-
# Accessing to functions (without stack)
#-
DEBUG_debug=false
. ${libIGCM}/libIGCM_debug/libIGCM_debug.ksh
. ${libIGCM}/libIGCM_card/libIGCM_card.ksh
#-
# Define the pattern string to substitute
#-
W_P='#-Q- '; W_W=${W_P}${x_t};
#-
# Extract list of 'config.card' files
# and create jobs with AA_job
#-
F_CFG='config.card';
for i in $(find ${d_n}/.. -name ${F_CFG} -print)
do
 j=$(cd ${i%/*};/bin/pwd;)
 n_f=${F_RCI##*/};

 if [ ! X$( echo ${j} | grep USER_SPEC ) = X ] ; then
 # Do not treat config.card if it is in sub-directory of USER_SPEC
 # Continue to next config.card
     continue
 else
     print - "\nWorking with file ${F_CFG}\nin directory ${j}\nfor ${n_f}";
 fi
 
 # Get all variables declared in section UserChoices in config.card
 IGCM_card_DefineArrayFromSection ${j}'/'${F_CFG} UserChoices
 # Set default values
 config_UserChoices_JobClass=mono
 config_UserChoices_JobNumProcTot=1
 config_UserChoices_UserSpec=""
 RESOL_ATM_3D=this_is_a_test_string
 RESOL=this_is_another_test_string
 typeset option
 for option in ${config_UserChoices[*]} ; do
     IGCM_card_DefineVariableFromOption ${j}'/'${F_CFG} UserChoices ${option}
 done

# Find the JobName : JobName might contain the variable RESOL_ATM_3D that will be replaced by what is in .resol file
 if [ ! X$( echo ${config_UserChoices_JobName} | grep ${RESOL_ATM_3D} ) = X ] ; then
    TRUERESOL=$( find ../ -name ".resol" -exec tail -1 {} \; | awk "-F=" '{print $2}' )
    JobName=$( echo ${config_UserChoices_JobName} | sed -e "s/${RESOL_ATM_3D}/${TRUERESOL}/" )
    IGCM_card_WriteOption ${j}'/'${F_CFG} UserChoices JobName ${JobName}
 elif [ ! X$( echo ${config_UserChoices_JobName} | grep ${RESOL} ) = X ] ; then
     TRUERESOL=$( find ../ -name ".resol" -exec head -1 {} \; )
     JobName=$( echo ${config_UserChoices_JobName} | sed -e "s/${RESOL}/${TRUERESOL}/" )
     IGCM_card_WriteOption ${j}'/'${F_CFG} UserChoices JobName ${JobName}
 else
     JobName=${config_UserChoices_JobName}
 fi
 echo "JobName=${JobName}"

# Add specific treatment for new type of directory structure 
  if [ -d ${j}/USER_SPEC ] && [ -d ${j}/GENERAL ] ; then
      echo "This is new configuration structure"

      if [ "X${config_UserChoices_UserSpec}" = X ] ; then
	echo "\nERROR in ${j}/config.card"
	echo "ins_job stops here"
	echo "=> The variable UserSpec must be added in config.card in section UserChoices"
	echo "=> UserSpec gives the directory for the .card configurtaion files for the wanted experiement. For exemple UserSpec=IPSLCM5/historical"
        exit 4
      else
	echo "UserSpec= ${config_UserChoices_UserSpec}"
      fi

      if [ -d ${j}/${JobName} ] ; then
	  echo "Directory ${j}/${JobName} exist already, continue next config.card"
	  continue
      fi
      cp -r ${j}/USER_SPEC/${config_UserChoices_UserSpec} ${j}/${JobName}
      cp -r ${j}/GENERAL/* ${j}/${JobName}/.
      cp -f ${j}/${F_CFG}  ${j}/${JobName}/.
      j=${j}/${JobName}
      echo new j=$j
  fi
# end specific treatment for new type directory structure 

 [[ -f ${j}'/'${n_f} ]] && { ins_job_Warning; } || \
  {
   print - "\nCopying file ${F_RCI}\nin directory ${j}";
   \cp ${F_RCI} ${j};
  }

 # File name for Job
 n_f='Job_'${JobName};
 [[ -f ${j}'/'${n_f} ]] && { ins_job_Warning; continue; }
 print - "\nWorking with file ${F_CFG}\nin directory ${j}\nfor ${n_f}";
 sed -e "/^${W_W} */ s///" \
     -e "/^${W_P}/d"       \
     -e "s%::modipsl::%${F_MOD}%" \
     -e "s/::Jobname::/${JobName}/" \
     -e "s/::JobClass::/${config_UserChoices_JobClass}/" \
     -e "s/::JobNumProcTot::/${config_UserChoices_JobNumProcTot}/" \
     ${F_JOB} > ${j}'/'${n_f}
 chmod u+x ${j}'/'${n_f}
done
#-
# Extract list of AA_* files in libIGCM
# and create jobs (for all except AA_job)
#-
for i in $(find ${libIGCM} -name "AA_*" -print | grep -v .svn )
do
 i_f=${i##*/};
 [[ ${i_f} = 'AA_job' ]] && { continue; }
 j=${i%/*}; n_f=${i_f#AA_}'.job';
 [[ -f ${j}'/'${n_f} ]] && { ins_job_Warning; continue; }
 print - "\nIn directory ${j}\n${i_f} -> ${n_f}"
 sed -e "/^${W_W} */ s///" \
     -e "s%::modipsl::%${F_MOD}%" \
     -e "/^${W_P}/d"       \
     ${i} > ${j}'/'${n_f}
 chmod u+x ${j}'/'${n_f}
done
#-
print - "";
#-
# That's all folks
#-
exit 0;
