#!/bin/bash
# $Id: env_make 728 2009-09-04 11:27:47Z bellier $
#---------------------------------------------------------------------
#- Loading an environment and optionally running Makefile
#---------------------------------------------------------------------
shopt -s extglob
#-
function env_make_Usage
{
echo -e "
${b_n} Loads an environment and runs a Makefile

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

Options :
  -h : help
  -v : verbose mode
  -m : dont'runs the Makefile

Defaults :
   runs the Makefile

Example for run a Makefile with target t_1 :
  ${b_n} t_1
"
}
#-
#  dirname  and  basename
#-
   d_n=${0%/*};  b_n=${0##*/};
#-
# Retrieving and validation of the options
#-
x_v='silencious'; x_m='run';
while getopts :hvm V
  do
   case ${V} in
    (h) env_make_Usage; exit 0;;
    (v) x_v='verbose';;
    (m) x_m='no_run';;
   (\?) echo ${b_n}" : -"${OPTARG}" option : not supported" 1>&2;
         exit 2;;
   esac
  done
shift $(($OPTIND-1));
#-
# Retrieve the target
#-
[[ ${#} -gt 1 ]] && \
  { echo 'Only one target can be specified' 1>&2; exit 3; }
x_t="";
[[ ${#} -eq 1 ]] && { x_t="${1}"; }
#-
# Test availability of the definition file
#-
tgt_f="${d_n}/.host_target"
[[ ! -f "${tgt_f}" ]] && \
 { echo -e "\\n${b_n} : file ${tgt_f} unreachable\\n"; exit 3; }
#-
# Extract the host name and update the Makefile name
#-
read tgt_n < ${tgt_f}
[[ -z "${tgt_n}" ]] && \
 { echo -e "\\n${b_n} : invalid host name\\n"; exit 3; }
mkf_n='Makefile'
#-
# Verbose mode
#-
[ ${x_v} = 'verbose' ] && \
 { echo -e "---";
   echo -e "Host     : ${tgt_n}";
   echo -e "Mode     : ${x_m}";
   echo -e "Makefile : ${mkf_n}";
   echo -e "Target   : ${x_t}";
   echo -e "---"; }
#-
# Loads the environment
#-
case ${tgt_n} in
 ("sx8mercure") \
  module load SX8
  module load netcdf_sx8
  ;;
 ("sx9mercure") \
  module load SX9
  module load netcdf_sx9
  ;;
 (*) \
  ;;
esac
#-
# [eventually] run the Makefile
#-
[[ "${x_m}" = 'run' ]] && { gmake -f ${mkf_n} ${x_t}; };
#-
exit 0;
