#! /bin/bash

# Copyright (c) 2018, University of Kaiserslautern
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
#    contributors may be used to endorse or promote products derived from
#    this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER
# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Author: Éder F. Zulian

simfiles="
ddr3-gem5-se.xml
"

bins="
8_cores
Bubblesort
chomp
exptree
FloatMM
IntMM
misr
Oscar
Perm
Puzzle
Queens
Quicksort
RealMM
Towers
Treesort
"

DIR="$(cd "$(dirname "$0")" && pwd)"
basedir="$DIR/../../.."
sfpath="../../DRAMSys/library/resources/simulations"
elf="DRAMSys_gem5"

if [[ -z "${GEM5}" ]]; then
	echo "GEM5 environment variable is undefined"
	exit 1
fi

proj_build() {
	if [[ $(hostname -s) =~ ^head[0-9]+$ ]] || [[ $(hostname -s) =~ ^node[0-9]+$ ]]; then
		# Elwetritsch cluster - heads or nodes
		module load qt/latest
		#module load anaconda3/latest
	fi
	cd $basedir
	rm -rf build
	mkdir -p build
	cd build
	qmake ../DRAMSys/DRAMSys.pro
	nprocs=$(cat /proc/cpuinfo | grep processor | wc -l)
	make -j$nprocs
}

proj_build

cd $basedir/build/gem5
if [ ! -f ${elf} ]; then
	echo "${elf} could not be found"
	exit 1
fi

for s in $simfiles; do
	sf="${sfpath}/${s}"
	sfn="${s%.*}"
	ext="${s##*.}"
	for bin in $bins; do
		`sed -i s/id=\".*\"/id=\"${sfn}_${bin}\"/g $sf`
		simulation="${sfpath}/${sfn}_${bin}.${ext}"
		cp $sf $simulation
		logfile=${sfn}_${bin}.log
		# LD_PRELOAD=/usr/lib/libtcmalloc.so ./${elf} ${simulation} ../../DRAMSys/gem5/gem5_se/${bin}/config.ini 1 > ${logfile} 2>&1 &
		date >> ${logfile}
		time ./${elf} ${simulation} ../../DRAMSys/gem5/gem5_se/${bin}/config.ini 1 >> ${logfile} 2>&1
		date >> ${logfile}
	done
done

