#!/bin/bash

# This is the master script to run an experiment. It is used to build
# and execute, and will do an optimized, debug, or valgrind run, with
# threads or not, utilizing the meson & ninja build system defined in
# meson.build.

# Usage: ./gproc.sh experimentname N
# N = 1 for normal GP run,
#     2 for GDB with threads
#     3 for GDB without threads
#     4 for valgrinding
#     5 for GDB with extra debug info
#     6 for profiling with valgrind's cachegrind

set -ex

# In practice this always works; then NTHREADS in #pragma omp parallel
# is followed properly and code works fast. To change number of
# threads, don't change this, but change nthreads below instead.
export OMP_NUM_THREADS=1

experimentdir=experiments/$1
compiletype=$2
compiledir=$experimentdir-build

# default values
extraflags="-march=native -Wall " # Any extra flags to give the compiler
nthreads=12
extradebug=0
bt=debug
exelist="gp" # hyptest gp"

[ -d $experimentdir ] && echo "Experiment directory, $experimentdir exists" && exit 1
[ -d $compiledir ] && echo "Compilation directory, $compiledir exists" && exit 1

case $compiletype in
    1) # Normal GP running here, maximum performance
	bt=release # FIXME we could add still -ljemalloc
	extraflags="$extraflags -g -Ofast "
	;;
    2) # Debug with GDB with 12 threads
	bt=debugoptimized
	;;
    3) # 3: Debug with GDB and a single thread
	nthreads=1
	extraflags="$extraflags "
	;;
    4) # 4: single thread with valgrind
	nthreads=1
	extraflags="$extraflags -Ofast -g "
	;;
    5) # Turn on extraverbose debugging in code
	nthreads=1
	extradebug=1
	;;
    6) # Profiling with cachegrind
	# extraflags="$extraflags -g -O2 -fno-omit-frame-pointer -fno-inline-functions -fno-inline-functions-called-once -fno-optimize-sibling-calls"
	extraflags="$extraflags -g -Ofast "
	;;
esac

# Compile here
mkdir "$compiledir"
export CC=gcc-8
CFLAGS="$extraflags -DNTHREADS=$nthreads -DDEBUG=$extradebug" meson --buildtype=$bt "$compiledir"
ninja -C "$compiledir"

# daydatas subdirectory is needed for outputting observations,
# srcfiles hold the program sources for reference.
mkdir -p "$experimentdir/daydatas" "$experimentdir/srcfiles"
cp *.c *.h "$experimentdir/srcfiles"
for e in $exelist; do cp "$compiledir"/$e "$experimentdir"; done

# create list of days that are simulated
./create_daylist.py $experimentdir

cd "$experimentdir"

exe="./gp" # or e.g. ./hyptest if an old file is resurrected from old_stuff

case $compiletype in
    [15])
	time $exe
	[ "$exe" == "./calibrate" ] && cd .. && ./plot_gp_calibration.py $experimentdir
	;;
    [23])
	gdb $exe
	;;
    4)
	valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=valgrind-out.txt $exe
	less valgrind-out.txt
	;;
    6)
	# valgrind --tool=cachegrind $exe
	valgrind --tool=callgrind $exe
	;;
esac

exit 0
