#!/bin/sh
#
# This script provides a suitable output for the search results.
#

# Clean preview results.
rm -f /tmp/tazpkgbox/search
touch /tmp/tazpkgbox/search

list_files()
{
	sed 's/.\[[01]m//g' | awk 'BEGIN { show=0 } {
		if (/^===/) show=1-show;
		else if (/^Package/) pkg=$2;
		else if ($0 != "" && show != 0) printf("%s %s\n",pkg,$0);
	}' | while read pkg file; do
		[ "$pkg" = "0" ] && continue
		version=$(grep -hs "^$pkg " /var/lib/tazpkg/packages.desc \
		  /var/lib/tazpkg/undigest/*/packages.desc | awk '{ print $3 }')
		if [ -d /var/lib/tazpkg/installed/$pkg ]; then
			if [ -x $file ]; then
				echo "exec|$pkg|$version|$file"
			elif [ -f $file ]; then
				echo "txt|$pkg|$version|$file"
			elif [ -d $file ] ; then
				echo "folder|$pkg|$version|$file"
			else
				# Missing installed file.
				echo "dialog-warning|$pkg|$version|$file"
			fi
		else
			echo "tazpkg|$pkg|$version|$file"
		fi
	done
}

list_package()
{
		if [ -d /var/lib/tazpkg/installed/$1 ]; then
			. /var/lib/tazpkg/installed/$1/receipt
			echo "tazpkg-installed|$PACKAGE|$VERSION|$SHORT_DESC"
		else
			echo "tazpkg|$PACKAGE|$VERSION|$SHORT_DESC"
		fi
}

search_package()
{
	IFS="|"
	cat /var/lib/tazpkg/packages.desc \
	    /var/lib/tazpkg/undigest/*/packages.desc 2> /dev/null | sort | \
	while read PACKAGE VERSION SHORT_DESC; do
	if echo "$PACKAGE $SHORT_DESC" | grep -iq "$SEARCH"; then
		list_package ${PACKAGE%% *}
	fi
	done 
	unset IFS
}

case "$1" in
	files)
		tazpkg search-file "$SEARCH" --mirror | list_files > \
			/tmp/tazpkgbox/search ;;
	packages)
		( search_package ;
		  for i in $(grep ^$SEARCH= /var/lib/tazpkg/packages.equiv | \
		          cut -d= -f2); do
		        SEARCH=${i#*:}
		        search_package
		  done ) > /tmp/tazpkgbox/search ;;
	tags)
		grep -ls TAGS /home/slitaz/wok/*/receipt | while read file; do
			TAGS=""
			. $file
			case "$TAGS" in
			*$SEARCH*) list_package $PACKAGE ;;
			esac
		done > /tmp/tazpkgbox/search ;;
	*)
		echo "Usage: $0 [packages|files|tags]" ;;
esac


exit 0
