#!/bin/ash

cd $(dirname $0)

## Load generic function
. 000-functions.sh

## setup default parameters
setupGlobalVar "APTS_SWITCH_DIR" "$(dirname $0)"
setupGlobalVar "APTS_HOST_DIR" "."
setupGlobalVar "APTS_HOST_IP" "$(netstat | grep nfsd | sed 's/.* \([0-9.]*\):nfsd.*/\1/')"
setupGlobalVar "APTS_HDL_18P" "/wr/lib/firmware/18p_mb-$(/wr/bin/shw_ver -f).bin"
setupGlobalVar "APTS_FW_RTCPU" "/wr/lib/firmware/rt_cpu.bin"


## Creating directories structure
mkdir ${APTS_SWITCH_DIR}/bin &> /dev/null
mkdir ${APTS_SWITCH_DIR}/logs &> /dev/null



# Run the scritps
run() 
{
	if [ x"$1" != x ]; then
		numseq="$1"
	else
		numseq="01 02 03 05 06 07 08 09 10 11"
	fi
	for itest in $numseq; do
		load_ask2run $(ls *${itest}-*.sh) $ask $update $inlog
	done
	

}


showhelp()
{
	echo ""
	echo "Usage: $0 [OPTION]... [TESTNUM]"
	echo ""
	echo "Testing script to check various components of the White Rabbit Switch"
	echo ""
	echo "if TESTNUM is not defined all tests will be executed in ascending order"
	echo ""
	echo "Options:"
	echo "	-h|--help 			Show this little message"
	echo "	-f|--force 			Don't ask to continue"
	echo "	-u|--update			Update binary files"
	echo "	-i|--inlog 			Create an independant log file for each test"
	echo "	-l|--list			List the different building steps"
	echo "	-s|--serial			Serial number"
	echo ""
	exit 0;
	
}


update="0"
inlog="0"
ask="1"
SN="0"

while [ $# -gt 0 ]; do    # Until you run out of parameters . . .
	case "$1" in
		-h|--help) showhelp;;
		-f|--force) ask="0";;
		-u|--update) update="1";;
		-i|--inlog) inlog="1";;
		-s|--serial) SN=$2; shift;;
		-l|--list) cd ${APTS_SWITCH_DIR}; ls 0*-*.sh; exit 0;;
		[0-9]*) num="$1";;
		*) showhelp;;
	esac
	shift       # Check next set of parameters.
done


# Obtain mac address
MAC=$(ifconfig | grep 'eth0'    | tr -s ' '    | cut -d ' ' -f5 | sed s/://g)
if [ "$MAC" != "02:34:56:78:9A:BC" ]; then
	SN=$(printf "%03d" 0x$(echo "$MAC" | tail -c 4))
fi

if [ ${SN} -eq "0" ]; then
	user_echoasking "num" "Type the serial number" "S/N"
	SN=$ans;
fi

echo "Starting test with WRS SN=${SN}"

export logfname="${APTS_SWITCH_DIR}/logs/output-${SN}"

# Put timestamp in the log
echo "" > $logfname.log
echo "-----------------------------------------------" >> $logfname.log
echo "$(date)" >> $logfname.log
echo "" >> $logfname.log


run "$num";

## Append all log to an history
cat $logfname.log >> ${logfname}_history.log
echo "" >> ${logfname}_history.log
chmod +r ${APTS_SWITCH_DIR}/logs/*
echo ""
echo "Test for switch ${SN} has terminated"
echo ""
cat $logfname.log 

exit 0;	
