#!/bin/bash
#
# test cook order
# Christian Mesh

CACHE="/home/slitaz/cache/"
broken="$CACHE/broken"

#Set to only use packages in the cooklist
LIST_ONLY="true"

tabs=0

list_push() {
	local val=$1
	index=${#list[*]}
	list[$index]=$val
}
list_pop() {
	index=$(expr ${#list[*]} - 1)
	unset list[$index]
}
list_contains() {
	local val=$1
	for element in ${list[*]}; do
		[ "$element" == "$val" ] && return 0
	done
	return 1
}


echo_indent() {
	for i in $(seq $(expr $tabs - 1)); 	do
		echo -en "|"
	done
	echo -en "-"
}
inc_tabs() { 
	tabs=$(expr $tabs + 1) 
}
dec_tabs() { 
	tabs=$(expr $tabs - 1)
}

add_pkg() {
	local pkg="$1"
	inc_tabs

	#package is a dep of package
	if list_contains $pkg ; then
		echo_indent && echo "CONFLICT $pkg"
		dec_tabs
		return
	fi

	#package is not in the list
	if [ "$LIST_ONLY" == "true" ] && (! grep -q "^$pkg$" $cooklist); then
		echo_indent && echo "$pkg is not in cooklist"
		dec_tabs
		return
	fi

	#package has already been processed
	if grep -q "^$pkg$" $newlist; then
		dec_tabs
		return
	fi
	
	list_push $pkg
	local WANTED
	local BUILD_DEPENDS
	source $wok/$pkg/receipt
	# The :: is for web interface color.
	echo_indent && echo "$pkg :: $WANTED $BUILD_DEPENDS"

	for dep in $WANTED $BUILD_DEPENDS; do
		add_pkg $dep
	done

	echo "$pkg" >> $newlist

	dec_tabs
	list_pop
}

order_list() {
	for pkg in $(cat $cooklist); do
		add_pkg $pkg
	done
}

list_wok() {
	file="$1"
	[ -f $file ] && rm $file
	for pkg in *; do
		echo "$pkg" >> $file
	done
}

# Log broken packages.
broken() {
	if ! grep -q "^$pkg$" $broken; then
		echo "$pkg" >> $broken
	fi
	exit 0
}

cook_list() {
	for pkg in $(cat $newlist)
	do
		echo "cooking $pkg"
		cook $pkg || broken
		sed -i /^${pkg}$/d $cooklist
	done
}

wok="/home/slitaz/wok/"
newlist="/root/cookutils/default.list"
cooklist="/root/cookutils/test.list"
rm $newlist
touch $newlist
#cd $wok && list_wok $cooklist
order_list
#cook_list
