#!/bin/sh
#
# author : A. Hebert
# use    : rskin [-c:|-q|-w|-p:]
#          -c name of compiler
#          -q quiet execution for regression testing
#          -w to execute in console (for debug purpose)
#          -p number of parallel threads (=1 by default)
#
System=`uname -s`
Sysx="`echo $System | cut -b -6`"
if [ $Sysx = "CYGWIN" ]; then
   MACH=`uname -o`
elif [ $Sysx = "AIX" ]; then
   MACH=`uname -s`
else
   MACH=`uname -sm | sed 's/[ ]/_/'`
fi

typ='custom'
quiet=0
term=0
nomp=0

while getopts ":c:qwp:" opt; do
  case $opt in
    c) typ="$OPTARG"
    ;;
    q) quiet=1
    ;;
    w) term=1
    ;;
    p) nomp=$OPTARG
    ;;
    \?) echo "Invalid option $opt -$OPTARG" >&2
    exit 1
    ;;
  esac

  case $OPTARG in
    -*) echo "Option $opt needs a valid argument"
    exit 1
    ;;
  esac
done

Code=`basename "$PWD"`
if [ $quiet = 0 ]; then
  echo 'execute with' $Code 'on system' $MACH 'with' $typ 'compiler'
fi

if [ -d "$MACH" ]; then
  if [ $quiet = 0 ]; then
  echo 'use the existing directory' $MACH
  fi
else
  echo 'creation of directory' $MACH
  mkdir "$MACH"
fi
CodeDir=$PWD

if [ $Sysx = "AIX" ]; then
  Tmpdir=/usr/tmp
elif [ $Sysx = "SunOS" ]; then
  Tmpdir=/var/tmp
else
  Tmpdir=/tmp
fi
inum=1
while [ -d $Tmpdir/rundir$inum ]
  do
  inum=`expr $inum + 1 `
done
Rundir=$Tmpdir/rundir$inum
mkdir $Rundir
if [ $quiet = 0 ]; then
  echo "RunDirectory:" $Rundir
fi
cd $Rundir

if [ $typ = 'custom' ]; then
  cp "$CodeDir"/bin/"$MACH"/Skin++ ./code
else
  cp "$CodeDir"/bin/"$MACH"'_'$typ/Skin++ ./code
fi

ln -s "$CodeDir"/data/* .

before=$(date +%s)
if [ $nomp != 0 ]; then
  echo 'number of OpenMP threads=' $nomp
  export OMP_NUM_THREADS=$nomp
  if command -v numactl >&2; then
    numactl --cpunodebind=0 --membind=0 2>/dev/null
    echo "use NUMA memory policy"
  fi
else
  export OMP_NUM_THREADS=1
fi
if [ $term = 0 ]; then
  ./code >result
else
  ./code
fi
if [ $quiet = 0 ]; then
  time=$(( $(date +%s) - before))
  printf 'End of execution. Total execution time: %dh %dmin %ds\n' \
    $(($time/3600)) $(($time%3600/60)) $(($time%60))
fi
mv result "$CodeDir"/"$MACH"
if [ $quiet = 0 ]; then
  echo 'the listing is located on ./'$MACH
fi

cd "$CodeDir"/"$MACH"
if [ $quiet = 0 ] && [ $term = 0 ]; then
  tail -25 result
elif [ $term = 0 ]; then
  RED='\033[0;31m'
  GREEN='\033[0;32m'
  NC='\033[0m' # No Color
  if tail result | grep -q "normal end" ; then
    printf "${GREEN}[OK]${NC}\n"
  else
    printf "${RED}[FAILED]${NC}\n"
  fi
fi
chmod -R 777 $Rundir
/bin/rm -r -f $Rundir
cd ..
