#!/bin/bash
#
# shell-script to call METIS from CODE_ASTER
#  $1 : data file for METIS (numerotation)
#       if $1="--version", it is passed to onmetis.exe
#  $2 : message level
#       if $2=0 outputs are redirected to /dev/null
#  $3 : result file (default fort.85)
#
# install directory
set_prefix() {
   local this=`readlink -n -f $1`
   prefix=`dirname $this`
}

set_prefix $0
METIS_INSTALL=$prefix

LD_LIBRARY_PATH=LD_LIB_PATH_VALUE:$LD_LIBRARY_PATH
export LD_LIBRARY_PATH

repinit=`pwd`
tmp_metis=$repinit/dir_metis

# arguments
if [ $# -lt 1 -o $# -gt 3 ]; then
   echo " usage : $0 data_file [message_level] [result_file]"
   exit 4
elif [ $# -eq 3 ]; then
   fileout=$3
   msg=$2
elif [ $# -eq 2 ]; then
   fileout=fort.85
   msg=$2
else
   msg=1
fi
arg="--version"
mkdir -p $tmp_metis
if [ "$1" != "--version" ]; then
   if [ ! -f "$1" ]; then
      echo "(F/U-METIS_1): $1 not found"
      exit 4
   fi
   cp -f "$1" $tmp_metis/fort.81
   arg="fort.81"
fi

# run onmetis.exe
cd $tmp_metis
if [ $msg -gt 0 ]; then
   $METIS_INSTALL/onmetis.exe $arg
   iret=$?
elif [ $msg -eq 0 ]; then
   $METIS_INSTALL/onmetis.exe $arg > /dev/null
   iret=$?
else
   echo "(F/U-METIS_2): Invalid argument"
   exit 4
fi
if [ $iret -eq 0 ] && [ "$1" != "--version" ]; then
  cp fort.85 $repinit/$fileout
fi

cd $repinit
rm -rf $tmp_metis
exit $iret
