#!/bin/bash

TMPDIR=/tmp
CACHEDIR=/ivo/Linvo/packlist_cache/$LINVO_RELEASE_WORKING_ON
METALIST_DIR=$LINVO_DIR/metalists/$LINVO_RELEASE_WORKING_ON

METALIST_TMP=$TMPDIR/metalist.sh.tmp
PACKLIST_TMP=$TMPDIR/packlist.sh.tmp

export LINVO_BUILD_TYPE=$1
	

if [ ! -e $CACHEDIR ]; then mkdir $CACHEDIR; fi
if [ ! -e $METALIST_DIR ]; then mkdir $METALIST_DIR; fi

gen_shell_script()
{
	#ARGUMENTS: $1 metalist, $2 shellscript
	echo ". $LINVO_DIR/scripts-infrastructure/metapacklib.sh" >> $2 #include library
	# replace ifdef with a definition check
	cat $1 | while read LINE
	do
		if [ "`echo \"$LINE\" | cut -d " " -f1`" == "ifdef" ]; then
			echo "if [ \"\$`echo \"$LINE\" | cut -d \" \" -f2`\" == \"TRUE\" ]; then " >> "$2"
 		else
			echo "$LINE" >> "$2"
		fi
	done
	chmod +x "$2"
}

add_to_list()
{
	#ARGUMENTS: $1 path to list, $2 check, $3 entry
	if [ ! "`grep \"$2\" \"$1\" 2>/dev/null`" ]; then
		echo "$3" >> $1
	fi
}

generate_zenity_dialog()
{
	#ARGUMENTS: $1 path to temporary file
	
	#void the previous file
	echo "" > $1
	
	#first, add the true by default arguments
	for LIST in `find $METALIST_DIR -name "*.metalist"`; do
		cat $LIST | while read LINE
		do
			if [ "`echo \"$LINE\" | cut -d " " -f1`" == "define_true" ]; then
				KEY="`echo \"$LINE\" | cut -d " " -f2`"
				ENTRY="True $KEY"
				add_to_list "$1" "$ENTRY" "$ENTRY"
			fi
		done
	done
	
	#second, add the other arguments as false
	for LIST in `find $METALIST_DIR -name "*.metalist"`; do
		cat $LIST | while read LINE
		do
			if [ "`echo \"$LINE\" | cut -d " " -f1`" == "ifdef" ]; then
				KEY="`echo \"$LINE\" | cut -d " " -f2`"
				ENTRY="False $KEY"
				add_to_list "$1" " $KEY" "$ENTRY"
			fi
		done
	done
}

parse_optins()
{
	for item in ${1//|/ }; do export $item="TRUE"; done
}

#generate_zenity_dialog /tmp/zenity_dialog.tmp
#enabled_options=`zenity --list --checklist --title "Linvo Build" --text "Configure Linvo LiveCD-${LINVO_BUILD_TYPE} build." --column "Enabled" --column "Option" $(cat /tmp/zenity_dialog.tmp)`
#parse_optins $enabled_options

( cd /ivo/Linvo/LinvoBuilding/gtk-configurator ; linvo-gtk-configurator $METALIST_DIR )
. /tmp/linvo_build_config

# parse the thing
#for LIST in `find $METALIST_DIR -name "*.metalist"`; do
#	#parsing list
#	echo "PARSING LIST: $LIST"
#	rm $METALIST_TMP 2>/dev/null
#	gen_shell_script $LIST $METALIST_TMP
#	$METALIST_TMP > $PACKLIST_TMP
#	PACKLIST=$CACHEDIR/`basename $LIST .metalist`.packlist
#	if [ "`diff $PACKLIST $PACKLIST_TMP 2>/dev/null`" ] || [ ! -e $PACKLIST ];
#	then
#		mv $PACKLIST_TMP $PACKLIST
#	fi
#	if [ ! "`cat $PACKLIST`" ]; then rm $PACKLIST; fi #remove empty packlists
#done

gen_packlist_from_metalist()
{
	echo "PARSING LIST: $1"
	rm $METALIST_TMP 2>/dev/null
	gen_shell_script $1 $METALIST_TMP
	$METALIST_TMP > $2
}

# end parsing the thing

