#!/bin/sh

#   Dec 03/1008 - F.Majaess (Revised for sa/saiph, ib/dorval-ib, af/alef)
#   Oct 16/2006 - F.Majaess (Revised for ma/maia, ns/naos)
#   Mar 01/2006 - F.Majaess (Revised for rg/rigel)
#   Feb 15/2005 - F.Majaess (Revised for AIX/Linux setup in Victoria)
#   Jun 20/2003 - F.Majaess (Revised for az/azur)
#   Feb 25/2002 - F.Majaess (Revised for ya/yata)
#   Feb 23/2000 - F.Majaess (Revised for kz/kaze and "sxf90")
#   Jun 14/1999 - F.Majaess (Added "modver" support)
#   Jan 21/1999 - F.Majaess (Added yo/yonaka)
#   Jul 14/1997 - F.Majaess (Added sx/hiru)
#   Mar 18/1996 - F.Majaess (revise for SX-4)
#   Nov 08/1994 - F.Majaess (Modify for sx3r and new destination identifiers)
#   May 10/1994 - E. Chan    (include ".s" file in output if it exists)
#   Jul 08/1993 - F. Majaess (add "$LINKEXT" to library list)
#   Oct 20/1992 - E. Chan

#id f77fil  - test compile and link a file containing Fortran source code 
#id           on either the front-end or one of the back-ends.

#   AUTHOR  - E. Chan

#hd PURPOSE - "f77fil" submits a job to the front-end or to one of the 
#hd           back-ends to compile and link the Fortran code contained in 
#hd           the specified file. The compiler is invoked using the 
#hd           environment variable '$F77'. On output, a compiled listing 
#hd           is returned if the target machine is one of the back-ends.
#hd
#hd           Variable dimensioned code may be used but the filename 
#hd           extension must be '.vd'. The script "genpgm" is invoked
#hd           and input parameters recognized by that script may be passed
#hd           to it through the "f77fil" command line.
#hd   
#hd           Any parameter specified on the command line with a '-'
#hd           immediately in front of it is passed on to the Fortran 
#hd           compiler as an option. These are in addition to those already
#hd           defined as part of the environment variable '$F77' used to 
#hd           invoke the compiler. Note that if an option is specified
#hd           more than once, the last value specified for that option
#hd           is used. This is useful in overriding options already turned 
#hd           on in '$F77'.  Options that require blanks between keywords
#hd           must be specified with underscores in place of the blanks.
#hd   
#hd           The linker may be turned off by specifying the '-c' option.
#hd     
#hd           The specified file may contain more than one subroutine. The 
#hd           '-c' option should always be used when compiling subroutines.
#hd           It is also possible to have more than one program in the file,
#hd           but this will cause an error with the linker unless the '-c'
#hd           option is used. 
#hd    
#hd           ************************************************************
#hd           *** The compiled listing should be printed out with the  ***
#hd           *** "li" script on the front-end which correctly handles ***
#hd           *** carriage controls contained in the printout. The     ***
#hd           *** script "lo" is NOT recommended.                      ***
#hd           ************************************************************

#pr PARAMETERS:
#pr   
#pr   POSITIONAL
#pr   
#pr       file = name of file containing Fortran source code
#pr              (filename may contain path information)
#pr   
#pr   PRIMARY
#pr          
#pr      Note: One of 'ha,,'sp','po','ca' or 'mz' is to be specified.
#pr
#pr         ha = to target job to IBM (hadar).
#pr
#pr         sp = to target job to IBM (spica).
#pr
#pr         po = to target job to Linux (pollux).
#pr
#pr         ca = to target job to Linux (castor).
#pr
#pr         mz = to target job to Linux (mez).
#pr
#pr       time = time limit in seconds (=200)
#pr   
#pr        mem = memory limit in megabytes (=>900 for IBM, =250 otherwise)
#pr     
#pr              The following options only apply to source code with 
#pr              variable dimensions (i.e. files with ".vd" extensions).
#pr     
#pr        bln = controls the number of longitudes for a subset
#pr              of the program library which handle large record
#pr              fields (1x1 grid) (=360)
#pr        blt = controls the number of latitudes  for a subset
#pr              of the program library which handle large record
#pr              fields (1x1 grid) (equator included)(=181).
#pr       ilev = number of model    levels (=30)
#pr        lat = number of grid latitudes  (=64)
#pr        lmt = m spectral truncation wave numbers (=42)
#pr        lon = number of grid longitudes (=128)
#pr        lrt = n spectral truncation wave numbers (=42)
#pr        plv = number of pressure levels (=30)
#pr        tsl = maximum time series length (=10241)
#pr        typ = spectral truncation type (0=rhomboidal, 2=triangular)
#pr              (=2)
#pr        modver = Model libary version to target for linking.
#pr                 (=\$DEFMODL).
#pr    

#ex EXAMPLES:
#ex   
#ex     f77fil pgm.vd ha modver=gcm6u
#ex     
#ex     The above example first passes the program source code contained in 
#ex     the file "pgm.vd" through the script "genpgm" and then submits a 
#ex     script called f77_pgm to Hadar to perform the test compilation 
#ex     and linking where the latter targets linkage with the appropriate 
#ex     "gcm6u" archive library.
#ex    
#ex     f77fil -c -L_fmtlist_page routine.f sx 
#ex
#ex     The above example test compiles on default SX-4 the subroutine
#ex     contained in the file "routine.f" with the additional compiler
#ex     options '-L fmtlist page'. 
#ex  

#  * Reset field separators (otherwise those defined in the parent process
#  * will be used and these may cause problems if they include special 
#  * characters used in this script). 

IFS=' '
export IFS

#  * Obtain the path of the current directory, then move into a temporary
#  * directory to execute the script.

cwd=`pwd`

#  * Obtain the submission file name and any specified option.

for arg in $@ 
do
  case $arg in 
       -*) arg=`echo $arg | tr '_' ' '` ;
           options="$options $arg"      ;;
      *=*) eval $arg                    ;;
      ha) mdest=${mdest:='hadar'}       ;;
      sp) mdest=${mdest:='spica'}       ;;
      po) mdest=${mdest:='pollux'}      ;;
      ca) mdest=${mdest:='castor'}      ;;
      mz) mdest=${mdest:='mez'}         ;;
        *) file=${file:=$arg}      
  esac
done

#  * Extract name and path information from the job filename. The 
#  * default directory containing the job is set to the parent
#  * directory. 

path=`expr $file : '\(.*\)/'`
code=`expr //$file : '.*/\(.*\)'`

path=${path:=$cwd}
  
if [ ! -f "$path/$code" ] ; then
  echo "Error: file $code does not exist"
  exit 1
fi

#  * Prompt for a destination if none was specified.

while [ -z "$mdest" ]
do
 if [ "$SITE_ID" = 'Victoria' ] ; then
   mdest="$HOSTID"
 elif [ "$SITE_ID" = 'York' ] ; then
   mdest="$HOSTID"
 elif [ "$SITE_ID" = 'Utor1' -o "$SITE_ID" = 'UOFT' ] ; then
   mdest="$HOSTID"
 elif [ "$SITE_ID" = 'Dorval' ] ; then
  echo "please enter a destination; ha/sp/po/ca/mz: > \\c"
  read tmdest
  case $tmdest in
      ha) mdest='hadar'                 ;;
      sp) mdest='spica'                 ;;
      po) mdest='pollux'                ;;
      ca) mdest='castor'                ;;
      mz) mdest='mez'                   ;;
       *) echo "illegal destination ! " ;;
  esac
 elif [ "$SITE_ID" = 'Downsview' ] ; then
   mdest="$HOSTID"
 else
  echo "please enter a destination: > \\c"
  read mdest
 fi
done

if [ "$SITE_ID" = 'Dorval' -a "$mdest" != 'hadar' -a "$mdest" != 'spica' -a "$mdest" != 'castor' -a "$mdest" != 'mez' -a "$mdest" != 'pollux' ] ; then
  echo "Invalid argument for machine destination $mdest"
  exit 4
fi

#  * Set the defaults.

time=${time:=200}
if [ "$mdest" = 'hadar' -o "$mdest" = 'spica' ] ; then
 mem=${mem:=900}
 if [ "$mem" -lt 900 ] ; then
  echo "Note: mem=$mem is changed to mem=900 "
  mem=900
 fi
else
 mem=${mem:=250}
fi
nonqs=${nonqs:=$NONQS}
nonqs=${nonqs:='no'}

if [ "$mdest" = 'hadar' ] ; then
  ext=.ha
elif [ "$mdest" = 'spica' ] ; then
  ext=.sp
elif [ "$mdest" = 'pollux' ] ; then
  ext=.po
elif [ "$mdest" = 'castor' ] ; then
  ext=.ca
elif [ "$mdest" = 'mez' ] ; then
  ext=.mz
fi

# setup for proper batch queue

queue=$mdest

Stamp="${HOSTID}_"`date +%Y%j%H%M%S`
mkdir -m 755 $HOME/tmp/tmp_f77fil_$$_$Stamp
cd $HOME/tmp/tmp_f77fil_$$_$Stamp
#
#  * Build script to do the compiling on the destination machine.
#

cat <<'endcat' > job
#!/bin/sh
#
Stamp="${HOSTID}_"`date +%Y%j%H%M%S`
mkdir -m 755 $CCRNTMP/tmp_f77fil_$$_$Stamp
cd $CCRNTMP/tmp_f77fil_$$_$Stamp
cat <<'endcat2' > source.f
endcat

#  * Process source code if variable dimensions are used (source code must
#  * have a ".vd" extension) and add to script.

vd=`expr $code : '.*\.vd$'`

if [ "$vd" -ne 0 ] ; then
  genpgm $path/$code mdest=$mdest noftp fdir=`pwd` \$xtra \
         ilev=$ilev lon=$lon lat=$lat lrt=$lrt lmt=$lmt \
          typ=$typ  plv=$plv bln=$bln blt=$blt tsl=$tsl \
         <<..end >f77fil.out$$
  y
..end
  if [ "$?" -ne 0 ] ; then
    echo "Error: problem in f77fil - check output file f77fil.out$$"
    mv f77fil.out$$ ..
    exit 2
  fi
  cat *.f >> job
else
  cat $path/$code >> job
fi

#  * Finish script by adding code to call the compiler and generate 
#  * listings.

cat <<endcat >> job
endcat2
echo 
set -x
modver="$modver"
modver=\${modver:=\$DEFMODL}

if [ -n "\$modver" ] ; then
  LOMODEL_ver=\`echo \$LOMODEL | eval sed 's/_model/_model_\${modver}/g'\`
else
 LOMODEL_ver="\$LOMODEL"
fi
\$F77 $options source.f \$LOMODEL_ver \$LOPLOT \$LODIAG \$LOCOMM \$LINKNCAR \$LINKEXT

set +x
if [ -f source.L ] ; then
  echo 
  cat source.L
fi
if [ -f source.lst ] ; then
  echo 
  cat source.lst
fi
cd ..
\rm -r tmp_f77fil_\$\$_\$Stamp
( rmllfls || : )
endcat
  
#  * Submit the job.

# qsub -q $queue job -lT $time -lM ${mem}mb -r f77_$code -eo \
#      -o $OUTPUTQ/${code}${ext}.$$ 

outdest="$OUTPUTQ/${code}${ext}.$$"
if [ "$nonqs" = 'yes' ] ; then
 if [ "$queue" = "$HOSTID" ] ; then
  if [ "$OS" = 'Linux' ] ; then
   Batch_job="/tmp/tmp_f77fil_job$$"
   echo "rm -f $Batch_job" >> job
   line="cat > $Batch_job ; chmod u+x $Batch_job ; nohup $Batch_job 1>>$outdest 2>>$outdest & " 
  else
   line="nohup sh -s - 1>>$outdest 2>>$outdest & "
  fi
 else
  echo "F77FIL: Sorry, nohup is limited to the same platform"
  echo "        queue=$queue; HOSTID=$HOSTID !"
  cd ..
  \rm -r tmp_f77fil_$$_$Stamp
  exit 1
 fi
else
 line="qsub -q $queue -lT $time -lM ${mem}mb -r f77_$code -eo -o $outdest"
fi
cat job | eval "$line"

#  * Remove temporary directory and exit script.

cd ..
\rm -r tmp_f77fil_$$_$Stamp

exit
