#!/bin/bash

# Run a command on all three repro scripts

# cd into the directory containing this script (from the bash faq 028)
if [[ $BASH_SOURCE = */* ]]; then
  cd -- "${BASH_SOURCE%/*}/" || exit
fi

outputfile=$$.repro.log

cleanup() {
    rm -f $outputfile
    exit
}

trap cleanup EXIT SIGINT

# Stop any running dockers
./stop-all-dockers

# Duoram
echo
echo Running Duoram repro
echo
( cd ../Docker && echo "Starting Duoram dockers" && echo && \
    ./start-docker && ./repro $* && echo "Stopping Duoram dockers" && \
    echo && ./stop-docker ) | tee $outputfile
if [ ${PIPESTATUS[0]} != "0" ]; then
    exit 1
fi

# Floram
echo
echo Running Floram repro
echo
( cd floram-docker && echo "Starting Floram dockers" && echo && \
    ./start-docker && ./repro $* && echo "Stopping Floram dockers" && \
    echo && ./stop-docker ) | tee -a $outputfile
if [ ${PIPESTATUS[0]} != "0" ]; then
    exit 1
fi

# Circuit ORAM
echo
echo Running Circuit ORAM repro
echo
( cd circuit-oram-docker/docker && echo "Starting Circuit ORAM dockers" && \
    echo && ./start-docker && ./repro $* && \
    echo "Stopping Circuit ORAM dockers" && \
    echo && ./stop-docker ) | tee -a $outputfile
if [ ${PIPESTATUS[0]} != "0" ]; then
    exit 1
fi

# Show stanzas starting with "# $1" and ending with "# " in the input
showstanza() {
    echo "# $1"
    sed -n "/# $1/,/# /{//!p;}"
}

echo
echo "===== Collated output ====="
echo

if [ "$1" == "test" ]; then
    cat $outputfile | showstanza 'Test output'
else
    cat $outputfile | showstanza 'Figure 7(a)'
    cat $outputfile | showstanza 'Figure 7(b)'
    cat $outputfile | showstanza 'Figure 7(c)'
    cat $outputfile | showstanza 'Figure 8(a)'
    cat $outputfile | showstanza 'Figure 8(b)'
    cat $outputfile | showstanza 'Figure 8(c)'
    cat $outputfile | showstanza 'Figure 9(a)'
    cat $outputfile | showstanza 'Figure 9(b)'
    cat $outputfile | showstanza 'Figure 9(c)'
    if [ "$DUORAM_EXTENDED_PLOTS" = "1" ]; then
	# Also show the plots for the extended version (Figures 11, 12)
	cat $outputfile | showstanza 'Figure 11(a)'
	cat $outputfile | showstanza 'Figure 11(b)'
	cat $outputfile | showstanza 'Figure 11(c)'
	cat $outputfile | showstanza 'Figure 12(a)'
	cat $outputfile | showstanza 'Figure 12(b)'
	cat $outputfile | showstanza 'Figure 12(c)'
    fi
fi