#!/bin/bash
set -x
export PATH=$PWD/tools/FCM/bin:$PATH

compil_mode_defined="FALSE"
compil_mode="prod"

arch_defined="FALSE"
parallel_defined="FALSE"
arch=""
parallel="none"
CPP_KEY="CPP_NONE" 

while (($# > 0))
  do
  case $1 in
      "-h") cat <<fin
Usage :
makegcm [options] -m arch exec
[-h]                       : help
[-prod / -dev / -debug]    : compilation en mode production (default) / developpement / debug .
 -arch nom_arch            : nom de l\'architecture cible
fin
	  exit;;

      "-prod")
	  compil_mode="prod" ; shift ;;

      "-dev")
	  compil_mode="dev" ; shift ;;

      "-debug")
	  compil_mode="debug" ; shift ;;

      "-arch")
	  arch=$2 ; arch_defined="TRUE"; shift ; shift ;;

      "-parallel")
	  parallel=$2 ; parallel_defined="TRUE"; shift ; shift ;;

      *)
	  code="$1" ; shift ;;
  esac
done

rm -f .void_file
echo > .void_file
rm -rf .void_dir
mkdir .void_dir

if [[ "$arch_defined" == "TRUE" ]]
then
  rm -f arch.path
  rm -f arch.fcm
  rm -f arch.env
  ln -s arch/arch-${arch}.path ./arch.path
  ln -s arch/arch-${arch}.fcm  ./arch.fcm
  if test -f arch/arch-${arch}.env
    then
      ln -s arch/arch-${arch}.env arch.env
    else
      ln -s .void_file arch.env
    fi
  source arch.env
  source arch.path
else
  echo "Veuillez definir une architecture cible"
  exit 1
fi

if [[ "$compil_mode" == "prod" ]]
then
  COMPIL_FFLAGS="%PROD_FFLAGS"
elif [[ "$compil_mode" == "dev" ]]
then
  COMPIL_FFLAGS="%DEV_FFLAGS"
elif [[ "$compil_mode" == "debug" ]]
then
  COMPIL_FFLAGS="%DEBUG_FFLAGS"
fi

if [[ "$parallel" == "mpi" ]]
then
  CPP_KEY="$CPP_KEY CPP_USING_MPI"
elif [[ "$parallel" == "none" ]]
then
  parallel="none"
else 
  echo "-parallel value $parallel is invalid, only permited <none> or <mpi>"
  exit 1
fi

ICOSA_LIB="$NETCDF_LIBDIR $HDF5_LIBDIR $NETCDF_LIB $HDF5_LIB"

rm -f config.fcm

echo "%COMPIL_FFLAGS $COMPIL_FFLAGS $NETCDF_INCDIR" >> config.fcm
echo "%CPP_KEY $CPP_KEY" >> config.fcm
echo "%LIB $ICOSA_LIB">> config.fcm

./build
