#!/bin/bash

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

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

FIBAPP=${BASEDIR}/apps/fib

EXPTYPES=${EXPTYPES:-"fibtbl-bu6502 fibiter-bu6502 fibtbl-figforth fibiter-figforth"}
INPUTS=${INPUTS:-"normal-10.5.20 input.0-19"}

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=${FIBAPP}/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" == *bu6502* ]] || [[ "$EXPTYPE" == *figforth* ]]; 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 ${FIBAPP}/inputs/${INPUT} ${EXPDIR}/inputs
	cd ${FIBAPP}/${EXPTYPE}
	if [[ "$EXPTYPE" == *bu6502* ]]; then
	    cp -r ${APPSDIR}/bu6502lib ${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/bu6502-img.mk ${EXPDIR}/inputs/Makefile
	    cp ${BU6502DIR}/6502 ${EXPDIR}/inputs
	elif [[ "$EXPTYPE" == *figforth* ]]; then
	    cp ${FIBAPP}/common/fib-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/figforth-img.mk ${EXPDIR}/inputs/Makefile
	    cp ${BU6502DIR}/6502 ${EXPDIR}/inputs
	elif [[ "$EXPTYPE" == *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/bochs-bin.mk ${EXPDIR}/inputs/Makefile
	    cp ${BOCHSDIR}/bochs ${EXPDIR}/inputs
	fi

	make -C ${EXPDIR}/inputs all
	if [[ "$EXPTYPE" == *bu6502* ]] || [[ "$EXPTYPE" == *figforth* ]]; then
	    cp ${APPSDIR}/makefiles/exptrace.mk ${EXPDIR}/Makefile
	    cd ${EXPDIR}
	    make trace; make data
	fi
    done
done
