#!/bin/sh

set -u
set -e
#set -x

TREE=tree
OUT=applications-all-users.vfolder-info

exec >$OUT

verarbeite_verzeichnis()
{
	echo -n "Bearbeite $1 ..." >&2

	BASN=`basename "$1"`
	DIR_FILE=`find "$1" -name *.directory -type f -maxdepth 1`

	[ -z "$DIR_FILE" ] && echo " skipped" >&2 && return
	
	echo "<Folder>"
	echo "	<Name>$BASN</Name>"
	#echo "	<OnlyUnallocated/>"
	echo "	<DontShowIfEmpty/>"
	echo "	<Desktop>`basename $DIR_FILE`</Desktop>"

	keywords_auswerten "$1"

	echo " done" >&2

	find "$1" -type d | sed 1d | while read a
		do	verarbeite_verzeichnis "$a"
	  done

	echo "</Folder>"
	echo
}

keywords_auswerten()
{
	[ -f "$1/and" -o -f "$1/or" -o -f "$1/not" ] || return 0
	echo "	<Query>"

	echo "		<And>"
	[ -f "$1/and" ] && cat "$1/and" | while read a
		do	[ -n "$a" ] && echo -e "\t\t\t<Keyword>$a</Keyword>"
	  done

	if [ -f "$1/or" ]
		then	echo -e "\t\t\t<Or>"
			cat "$1/or" | while read a
				do	[ -n "$a" ] && echo -e "\t\t\t\t<Keyword>$a</Keyword>"
			  done
			echo -e "\t\t\t</Or>"
	  fi
	  
	[ -f "$1/not" ] && cat "$1/not" | while read a
		do	[ -n "$a" ] && echo -e "\t\t\t<Not><Keyword>$a</Keyword></Not>"
	  done

	echo "		</And>"

	echo "	</Query>"
}

cat header.vfolder

find "$TREE" -type d -maxdepth 1 | sed 1d | while read a
	do	verarbeite_verzeichnis "$a"
  done

cat footer.vfolder