#!/bin/bash
# Wrapper script for stanc, the stan compiler
#
# File suffix for data
FSDATA='Rdata'
#
# File suffix for samples files
SFSUFF='csv'
#
EXEC='/usr/bin/stanc'
CC='/usr/bin/g++'
OPTIMIZE='-O3'
INCLUDE="-I/usr/include/stan \
-I/usr/include/stan/lib/eigen_3.1.2 \
-I/usr/include/stan/lib/boost_1.52.0"

if test -z "$1" ; then
	echo 'stan'
	echo 'Wrapper script for the stanc compiler'
	echo 'Usage: stan <name_of_module>'
	echo '       stan --clean <name_of_module>'
	echo '       stan --run   <name_of_module> [OPTS ...]'
	echo '       stan --init  [TARGET_DIRECTORY]  (default: ./stan)'
	exit 1
fi

if test "$1" == '--clean' ; then
	if test -z "$2" ; then
		echo 'Missing <name_of_module>'
		echo 'Usage: stan --clean <name_of_module>'
		exit 1
	fi

	if ! test -x "$2" ; then
		echo "Executable module: $2     not found"
	else
		rm -f "$2"
		echo "Removing executable:    $2"
	fi

	if ! test -f "$2.cpp" ; then
		echo "Source of module:  $2.cpp not found"
	else
		rm -f "$2.cpp"
		echo "Removing module source: $2.cpp"
	fi

	if test -f "$2.$SFSUFF" ; then
		rm -f "$2.$SFSUFF"
		echo "Removing sample file:   $2.$SFSUFF"
	fi
	exit 0
fi

if test "$1" == '--run' ; then
	if ! test -f "$2.$FSDATA" ; then
		DATA=''
	else
		DATA="--data=$2.$FSDATA"
	fi

	if ! test -x "$2" ; then
		echo "Executable module $2 not found"
	else
		MODULE="$2"
		shift 2
		OUT="--samples=$MODULE.$SFSUFF"
				
		echo "Running $MODULE $DATA $OUT $@"
		./$MODULE $DATA "$OUT" "$@"
	fi
	exit $?
fi

# Initialize stan compiler environment in userspace
if test "$1" == '--init' ; then
	shift 1

	if ! test -x /usr/bin/stanc ; then
		echo "Please install package stan"
		exit 1
	fi

	if ! test -d /usr/share/stan ; then
		echo "Please install package stan-devel-static"
		exit 1
	fi

	if test -z "$1" ; then
		TARGET='./stan'
	else
		TARGET="$1"
	fi

	if ! test -d $TARGET ; then
		mkdir -p $TARGET
	fi

	if ! test -d $TARGET/models ; then
		cp -r /usr/share/stan/models $TARGET/
	else
		echo "$TARGET/models/ exists; skipping copy operation"
	fi

	exit 0
fi

# Compile module
if ! test "$1.stan" ; then
	echo "Module $1.stan not found"
	exit 1
fi

SEARCH="--name=$1 --o=$1.cpp $1.stan"
$EXEC $SEARCH
echo "$CC $OPTIMIZE $INCLUDE $1.cpp -o $1 -lstan"
$CC $OPTIMIZE $INCLUDE $1.cpp -o $1 -lstan
