#!/bin/bash

function readarray ()
{
	read -r
	while [ $? -eq 0 ] ; do
		eval LENGTH=\$\{\#$1\[\@\]\} ;
		eval $1[\$LENGTH]=\$REPLY ;
		read -r ;
	done
}

function readfieldarray ()
{
	eval "awk -F', *' -- '{ print \$$2; }' > generate.sh.temp2"
	eval "readarray $1 < generate.sh.temp2"
	rm generate.sh.temp2
}

function mkdirifnotexists ()
{
	if [ -a "$1" ] ; then
		if [ ! -d "$1" ] ; then
			echo "Required directory name already used by file $1 !! aborting ..." ;
			exit 1 ;
		fi ;
	else
		eval mkdir $1 ;
	fi
}

PREFFIX="$1"
SESSION_NAME="$2"
CSV_FILE="$3"
FIELDS="WINDOW_TYPE WINDOW_NUMBER WINDOW_NAME_UNESCAPED WINDOW_NAME_ESCAPED"
declare -a $FIELDS

eval "grep -Ev '^#' < $CSV_FILE > generate.sh.temp1"

declare -i FIELD_NUMBER=0
for FIELD in $FIELDS ; do
	FIELD_NUMBER+=1 ;
	eval "readfieldarray $FIELD $FIELD_NUMBER < generate.sh.temp1"
done

#for FIELD in $FIELDS ; do
#	echo +++ $FIELD +++ ;
#
#	eval LENGTH=\$\{\#$FIELD\[\@\]\} ;
#	for (( COUNT=0 ; COUNT<$LENGTH ; COUNT++ )) ; do
#		eval RESULT=\$\{$FIELD\[\$COUNT\]\} ;
#		eval echo \'$RESULT\' ;
#	done ;
#
#	echo --- $FIELD --- ;
#	echo
#done

eval "LENGTH=\`wc -l generate.sh.temp1 | awk -- '{ print \$1; }'\`"

rm generate.sh.temp1

eval pushd \'$PREFFIX/$SESSION_NAME\' >/dev/null 2>&1
for (( COUNT=0 ; COUNT<$LENGTH ; COUNT++ )) ; do
	eval mkdirifnotexists \'${WINDOW_NAME_ESCAPED[$COUNT]}\'
done ;
popd >/dev/null 2>&1

for (( COUNT=0 ; COUNT<$LENGTH ; COUNT++ )) ; do
	if [ ! -z ${WINDOW_TYPE[$COUNT]} ] ; then
		if [ ${WINDOW_TYPE[$COUNT]} == "main" ] ; then
			MAIN=$COUNT
		fi

		eval pushd \'${WINDOW_TYPE[$COUNT]}\' >/dev/null 2>&1
		M4_DIR=`pwd`
		M4_FILES=`echo *`
		popd >/dev/null 2>&1
		if [ "$M4_FILES" == '*' ] ; then
			M4_FILES=
		fi

		eval M4_DEFS=\" -DPREFFIX=\'$PREFFIX\' -DSESSION_NAME=\'$SESSION_NAME\'\"
		for FIELD in $FIELDS ; do
			eval FIELD_VALUE=\"\$\{$FIELD\[\$COUNT\]\}\"
			M4_DEFS="$M4_DEFS -D$FIELD='$FIELD_VALUE'"
		done

		eval pushd $PREFFIX/$SESSION_NAME/${WINDOW_NAME_ESCAPED[$COUNT]} >/dev/null 2>&1
		for M4_FILE in $M4_FILES ; do
			if [ $M4_FILE != ${M4_FILE%.m4} ] ; then
				eval m4 $M4_DEFS $M4_DIR/$M4_FILE > ${M4_FILE%.m4}
			fi
		done
		popd >/dev/null 2>&1
	fi

done ;


for (( COUNT=0 ; COUNT<$LENGTH ; COUNT++ )) ; do
	APPENDTOMAIN_DIR=$PREFFIX/$SESSION_NAME/${WINDOW_NAME_ESCAPED[$COUNT]}

	eval pushd $PREFFIX/$SESSION_NAME/${WINDOW_NAME_ESCAPED[$COUNT]} >/dev/null 2>&1
	APPENDTOMAIN_FILES=`echo *`
	popd >/dev/null 2>&1
	if [ "$APPENDTOMAIN_FILES" == '*' ] ; then
		APPENDTOMAIN_FILES=
	fi

	eval pushd $PREFFIX/$SESSION_NAME/${WINDOW_NAME_ESCAPED[$MAIN]} >/dev/null 2>&1
	for APPENDTOMAIN_FILE in $APPENDTOMAIN_FILES ; do
		if [ $APPENDTOMAIN_FILE != ${APPENDTOMAIN_FILE%.appendtomain} ] ; then
			eval cat $APPENDTOMAIN_DIR/$APPENDTOMAIN_FILE >> ${APPENDTOMAIN_FILE%.appendtomain}
			eval rm $APPENDTOMAIN_DIR/$APPENDTOMAIN_FILE
		fi
	done
	popd >/dev/null 2>&1
done ;
