#!/bin/bash

if [[ -z "$BASEDIR" ]]; then
  echo Error: BASEDIR not set
  exit
fi

if [[ -z "$EXPTYPES" ]]; then
  echo Error: EXPTYPES not set
  exit
fi

if [[ -z "$INPUTS" ]]; then
  echo Error: INPUTS not set
  exit
fi

BU6502DIR=${BASEDIR}/6502
BOCHSDIR=${BASEDIR}/psml-bochs/bochs/REL_2_6_2_FINAL/bochs
COMPRESSDIR=${BASEDIR}/compress
APPSDIR=${BASEDIR}/apps

for EXPTYPE in $EXPTYPES; do
    for INPUT in $INPUTS; do
	export INPUT
	export EXPTYPE
	TS=$(date +'%d-%m-%y-%H-%M')

	EXP=${EXPTYPE}_${INPUT}_${TS}
	EXPDIR=${BASEDIR}/data/${EXP}
	mkdir -p $EXPDIR

	    mkdir ${EXPDIR}/src
	    cd ${COMPRESSDIR}
	    find . -type f -name '*.[hc]' -print -o -name 'Makefile' -print -o -name 'octplt*' -print | grep -v uthash | sed 's:./::' | tar zcf ${EXPDIR}/src/compress.tar.gz -T -
	    if [[ "$EXPTYPE" == *6502* ]]; then
		cd ${BU6502DIR}; make 6502
		find . -type f -name '*.[hc]' -print -o -name 'Makefile' -print | grep -v apps/cc/apps | grep -v apps/cc/install | grep -v grade/ | grep -v writeup | grep -v fibexp/ | sed 's:./::' | tar zcf ${EXPDIR}/src/6502.tar.gz -T -
	    elif [[ "$EXPTYPE" == *newlib* ]]; then
		cd ${BOCHSDIR}; make bochs
		find . -type f -name '*.[hc]' -print -o -name '*.cc' -print -o -name 'config.log' -print -o -name 'Makefile' -print | sed 's:./::' | tar zcf ${EXPDIR}/src/bochs.tar.gz -T -
	    fi

	    mkdir ${EXPDIR}/inputs
	    cp ${SIMPLEAPP}/inputs/${INPUT} ${EXPDIR}/inputs
	    cd ${SIMPLEAPP}/${EXPTYPE}
	    if [[ "$EXPTYPE" == *6502-cc65* ]]; then
		cp -r ${APPSDIR}/cc65lib ${EXPDIR}
     		find . ! -name . -prune -type f -name '*.[hc]' -print -o -name '*.cfg' -print | while read srcfile; do cp $srcfile ${EXPDIR}/inputs; done
		cp ${APPSDIR}/makefiles/6502-cc65_img.mk ${EXPDIR}/inputs/Makefile
		cp ${BU6502DIR}/6502 ${EXPDIR}/inputs
	    elif [[ "$EXPTYPE" == *6502-figforth* ]]; then
		cp ${SIMPLEAPP}/common/simple-fig.s ${EXPDIR}/inputs
     		find . ! -name . -prune -type f -name '*.s' -print -o -name '*.cfg' -print | while read srcfile; do cp $srcfile ${EXPDIR}/inputs; done
		cp ${APPSDIR}/makefiles/6502-figforth_img.mk ${EXPDIR}/inputs/Makefile
		cp ${BU6502DIR}/6502 ${EXPDIR}/inputs
	    elif [[ "$EXPTYPE" == *bochs32-newlib* ]]; then
		cp -r ${APPSDIR}/newlibsys ${EXPDIR}
     		find . ! -name . -prune -type f -name '*.[hc]' -print -o -name '*.bochsrc' -print | while read srcfile; do cp $srcfile ${EXPDIR}/inputs; done
		cp ${APPSDIR}/makefiles/bochs32-newlib_bin.mk ${EXPDIR}/inputs/Makefile
		cp ${BASEDIR}/psml-bochs/bios/protected_bios.s ${EXPDIR}/inputs
		cp ${BOCHSDIR}/bochs ${EXPDIR}/inputs
		cp ${EXPDIR}/inputs/${INPUT} ${EXPDIR}/inputs/${EXPTYPE}.in
	    fi
	    make -C ${EXPDIR}/inputs all

	    if [[ "$EXPTYPE" == *6502* ]]; then
		cp ${APPSDIR}/makefiles/6502_trace.mk ${EXPDIR}/Makefile
#		cd ${EXPDIR}; make trace; make data
	    elif [[ "$EXPTYPE" == *bochs32* ]]; then
		cp ${APPSDIR}/makefiles/bochs32_trace.mk ${EXPDIR}/Makefile
#		cd ${EXPDIR}; make trace; make data
	    fi
	done
    done
done
