#!/bin/bash

export MLT_PROFILE=dv_pal
export LC_NUMERIC=C

function show_consumers( )
{
	awk -F '\t' '{ printf( "%d. %s\n", ++ i, $1 ); }' < consumers.ini
}

function get_consumer( )
{
	option=$1
	[ "$option" != "" ] && [ $option -gt 0 ] && sed 's/\t\+/\t/g' < consumers.ini | cut -f 2 | head -n $option | tail -n -1
}

function show_menu( )
{
	sed 's/\t\+/\t/g' < demo.ini |
	awk -F '\t' '{ printf( "%2d. %-30.30s", ++ i, $2 ); if ( i % 2 == 0 ) printf( "\n" ); } END { if ( i % 2 == 1 ) printf( "\n" ); }'
}

function check_dependencies( )
{
	option=$1
	if [ $option -gt 0 ]
	then
		deps=`sed 's/\t\+/\t/g' < demo.ini | cut -f 3 | head -n $option | tail -n -1`
		if [ "$deps" != "" ]
		then
			echo "$deps" | 
			tr ',' '\n' | 
			while read dep 
			do
				ls $dep > /dev/null 2>&1
				val=$?
				[ $val != 0 ] && echo Failed to find $dep >&2 && echo $val
			done
		fi
		echo 0
	fi
}

function get_demo( )
{
	option=$1
	if [ $option -gt 0 ]
	then
		cut -f 1 demo.ini | head -n $option | tail -n -1
	fi
}

while [ 1 ]
do

	echo Select Consumer
	echo

	show_consumers

	echo
	echo 0. Exit
	echo
	echo -n "Option: "
	read option
	echo

	[ "$option" == "0" ] && break

	export MLT_CONSUMER=`get_consumer $option`

	while [ "$option" != "0" -a "$MLT_CONSUMER" != "" ]
	do
		echo Choose Demo
		echo
	
		show_menu
	
		echo
		echo -n "Option: "
		read option
		echo

		[ "$option" == "" ] && break
	
		demo=`get_demo $option`
		usable=`check_dependencies $option`
	
		if [ "$usable" = "0" -a "$demo" != "" ]
		then
			if [ "$MLT_CONSUMER" == "xml:" ]
			then	export XML_CONSUMER="xml:$demo.mlt"
					bash $demo -consumer $XML_CONSUMER
					melt +$demo.txt out=100 $demo.mlt $demo.mlt -filter watermark:watermark1.png composite.fill=1 composite.geometry=85%/5%:10%x10%
			elif [ "$MLT_CONSUMER" == "xml" ]
			then	bash $demo -consumer $MLT_CONSUMER | less
			else	bash $demo -consumer $MLT_CONSUMER
			fi
		elif [ "$usable" != "" ]
		then
			echo 
			echo Unable to locate suitable files for the demo - please provide them.
			read pause
		fi
	
		stty sane
	done

done
