#!/bin/sh
# Tazwok - SliTaz source compiler and binary packages generator/cooker.
#
# Tazwok can compile source packages and create binary packages suitable for
# Tazpkg (Tiny Autonomous zone package manager). You can build individual
# packages or a list of packages with one command, rebuild the full distro,
# generate a packages repository and also list and get info about packages.
#
# (C) 2007-2009 SliTaz - GNU General Public License.
#

VERSION=4.2
. /usr/lib/slitaz/libtaz
source_lib commons

# Use text instead of numbers, don't get $2 here if it's an option.
[ "$2" = "${2#--}" ] && PACKAGE=$2 && LIST=$2 && ARG=$2
COMMAND=$1

########################################################################
# TAZWOK USAGE
########################
# Print the usage (English).

usage()
{
	echo -e "\nSliTaz sources compiler and packages generator - Version: $VERSION\n
\033[1mUsage: \033[0m `basename $0` [command] [package|list|category|dir|id] [--option]
\033[1mCommands: \033[0m\n
  usage          Print this short usage.
  stats          Print Tazwok statistics from the config file and the wok.
  edit           Edit a package receipt in the current wok.
  build-depends  Generate a list of packages to build a wok.
  list           List all packages in the wok tree or by category.
  info           Get information about a package in the wok.
  report         Display commit/cooklist/broken/blocked.
  check          Check every receipt for common errors.
  check-log      Check the process log file of a package.
  check-depends* Check every receipt for DEPENDS - doesn't scan ELF files.
  check-src      Check upstream tarball for package in the wok.
  search         Search for a package in the wok by pattern or name.
  compile        Configure and build a package using the receipt rules.
  genpkg         Generate a suitable package for Tazpkg with the rules.
  cook           Compile and generate a package directly.
  cook-list      Cook all packages specified in the list by order.
  cook-commit    Cook all modified receipts.
  cook-all       Cook all packages excepted toolchain.
  cook-toolchain Cook the toolchain packages.
  gen-cooklist   Generate a sorted cooklist using packages or list.
  sort-cooklist  Sort the cooklist given in argument.
  get-src        Download the tarball of the package given in argument.
  clean          Clean all generated files in the package tree.
  new-tree       Prepare a new package tree and receipt (--interactive).
  gen-list       (Re-)Generate a packages list for a repository.
  check-list     Update packages lists for a repository.
  gen-wok-db     (Re-)Generate wok lists with depends and wanted datas.
  gen-clean-wok  Generate a clean wok in a dir.
  clean-wok      Clean entirely the wok.
  clean-src       Remove old/unrelated-to-wok sources.
  remove         Remove a package from the wok.
  webserver      Enable/disable webserver on localhost.
  update-wok     Update the wok.
  maintainers    List all maintainers in the wok.
  maintained-by  List packages maintained by a contributor.
  tags           List all tags used in wok receipts.
  block          Add package from the blocked list to prevent cooking it.
  unblock        Remove package from the blocked list.\n
 
 You can use `basename $0` command --help to list avaible options.
 \033[1mImportant - *: \033[0m Commands which need a rewrite."
}

# This function display an error message without returning any error code.
# It also log the message in source package's warnings.txt; this file can be
# used on an eventual package page on website to display cooking warnings.
tazwok_warning()
{
	echo -e "tazwok: $1" >&2
	echo -e "$1" >> $WOK/${WANTED:-$PACKAGE}/warning.txt
	return
}

########################################################################
# TAZWOK VARIABLES & INITIAL CONFIGURATION
########################

get_tazwok_config()
{
	# Get configuration file.
	get_config

	# Define & get options.
	get_options_list="$get_options_list SLITAZ_DIR SLITAZ_VERSION undigest"
	get_options

	LOCAL_REPOSITORY=$SLITAZ_DIR/${undigest:-$SLITAZ_VERSION}
	
	if ! [ "$save_dir" ]; then
		if [ -f $LOCAL_REPOSITORY/tazwok.conf ] || [ -f $LOCAL_REPOSITORY/slitaz.conf ]; then
			save_dir=$LOCAL_REPOSITORY
			[ -f $LOCAL_REPOSITORY/slitaz.conf ] && source $LOCAL_REPOSITORY/slitaz.conf
			cd $save_dir
			get_tazwok_config
			unset save_dir
			return
		fi
	fi
	
	# The path to the most important files/dir used by Tazwok.
	PACKAGES_REPOSITORY=$LOCAL_REPOSITORY/packages
	WOK=$LOCAL_REPOSITORY/wok
	INCOMING_REPOSITORY=$LOCAL_REPOSITORY/packages-incoming
	SOURCES_REPOSITORY=$LOCAL_REPOSITORY/src
	set_common_path

	# /!\ This part needs some changes.
	# Basically, get theses files from the net if they are missing.
	dep_db=$INCOMING_REPOSITORY/wok-depends.txt
	wan_db=$INCOMING_REPOSITORY/wok-wanted.txt

	# Check commons directories, create them if user is root.
	if test $(id -u) = 0 ; then
		check_dir $WOK || chmod 777 $WOK
		check_dir $LOCAL_REPOSITORY/clean-wok || chmod 777 $LOCAL_REPOSITORY/clean-wok
		check_dir $PACKAGES_REPOSITORY
		check_dir $SOURCES_REPOSITORY
		check_dir $INCOMING_REPOSITORY
		check_dir $LOCAL_REPOSITORY/log
		[ -f $dep_db ] || touch $dep_db
		[ -f $wan_db ] || touch $wan_db
		[ -f $PACKAGES_REPOSITORY/cookorder.txt ] || touch $PACKAGES_REPOSITORY/cookorder.txt
		for file in broken blocked commit incoming cooklist; do
			[ ! -f $PACKAGES_REPOSITORY/$file ] && touch $PACKAGES_REPOSITORY/$file
		done
		touch $SOURCES_REPOSITORY/sources.list
	fi

	# Limit memory usage.
	ulimit -v $(awk '/MemTotal/ { print int(($2*80)/100) }' < /proc/meminfo)

	# log steps for webserver.
	log_step="$LOCAL_REPOSITORY/log/step"
	run_on_exit="$run_on_exit
rm -f $LOCAL_REPOSITORY/log/step
rm -f $LOCAL_REPOSITORY/log/package"
}

# Used in several functions.
set_common_path()
{
	# The receipt is used to compile the source code and
	# generate suitable packages for Tazpkg.
	RECEIPT="$WOK/$PACKAGE/receipt"

	# The path to the process log file.
	LOG="$WOK/$PACKAGE/process.log"
}

########################################################################
# TAZWOK CHECK FUNCTIONS
########################

# Check for a package name on cmdline.
check_for_package_on_cmdline()
{
	if [ ! "$PACKAGE" ]; then
		echo -e "\nYou must specify a package name on the command line." >&2
		echo -e "Example : tazwok $COMMAND package\n" >&2
		exit 1
	fi
}

# Check for the receipt of a package used to cook.
check_for_receipt()
{
	if [ ! -f "$RECEIPT" ]; then
		echo -e "\nUnable to find the receipt : $RECEIPT\n" >&2
		exit 1
	fi
}

# Check for a specified file list on cmdline.
check_for_list()
{
	if [ ! "$LIST" ]; then
		echo -e "\nPlease specify the path to the list of packages to cook.\n" >&2
		exit 1
	fi
	
	# Check if the list of packages exists.
	if [ -f "$LIST" ]; then
		LIST=`cat $LIST`
	else
		echo -e "\nUnable to find $LIST packages list.\n" >&2
		exit 1
	fi
	
	if [ ! "$LIST" ]; then
		echo -e "\nList is empty.\n" >&2
		exit 1
	fi
}

check_for_pkg_in_wok()
{
	[ -f $WOK/$PACKAGE/receipt ] && return
	if [ "$undigest" ]; then
		[ -f "$SLITAZ_VERSION/wok/$PACKAGE/receipt" ] && return 1
		grep -q ^$PACKAGE$ $SLITAZ_DIR/$SLITAZ_VERSION/packages/packages.txt && return 1
	fi
	echo "Can't find $PACKAGE in wok or mirror" >&2
	return 2
}

########################################################################
# TAZWOK CORE FUNCTIONS
########################

remove_src()
{
	[ "$WANTED" ] && return
	look_for_cookopt !remove_src && return
	if [ ! -d $WOK/$PACKAGE/install ] && [ "$src" ] && [ -d "$src/_pkg" ]; then
		check_for_var_modification _pkg src || return
		mv "$src/_pkg" $WOK/$PACKAGE/install
	fi
	
	# Don't remove sources if a package use src variable in his
	# genpkg_rules: it maybe need something inside.
	for i in $PACKAGE $(look_for_rwanted); do
		sed -n '/^genpkg_rules\(\)/','/}/'p $WOK/$i/receipt | \
			fgrep -q '$src' && tazwok_warning "Sources will not be removed \
because $i use \$src in his receipt." && return
	done
	
	report step "Removing sources directory"
	rm -fr "$src"
	report end-step
}

# Check $COOK_OPT; usage : get_cookopt particular_opt
# Return error if not founded
# Return args if the opt is in the format opt=arg1:arg2:etc
look_for_cookopt()
{
	for arg in $COOK_OPT; do
		case $arg in
			$1=*)
				arg=${arg#$1=}
				while [ "$arg" ]; do
					echo "${arg%%:*}"
					[ "${arg/:}" = "$arg" ] && return
					arg=${arg#*:}
				done
			;;
			$1)
				return
			;;
		esac
	done
	return 1
}

# Check for the wanted package if specified in WANTED
# receipt variable. Set the $src/$_pkg variable to help compile
# and generate packages.
check_for_wanted()
{
	if [ "$WANTED" ]; then
		report "Checking for the wanted package"
		if [ ! -d "$WOK/$WANTED" ]; then
			report exit "\nWanted package is missing in the work directory.\n"
		fi
		
		# Checking for buildtree of Wanted package
		if [ ! -d "$WOK/$WANTED/taz" ]; then
			echo -e "\n\nSource files of wanted package is missing in the work directory."
			echo -n "Would you like to build the missing package (y/N) ? " ; read anser
			if [ "$anser" == "y" ]; then
				tazwok cook $WANTED
			else
				report exit "\nWanted package source tree is missing in the work directory.\n"
			fi
		fi
		report end-step
		
		# Set wanted src path.
		set_src_path && set_pkg_path
		
	fi
}

# Check for build dependencies, notify user and install if specified.
check_for_build_depends()
{
	[ "$WANTED" ] && return
	[ "$CATEGORY" = meta ] && ! fgrep -q compile_rules $RECEIPT && return
	[ ! "$BUILD_DEPENDS" ] && ! fgrep -q compile_rules $RECEIPT && return
	report step "Looking for build dependencies"

	# Keep the list of previously installed build_depends then compare
	# it with new build_depends to know what to install and what to
	# what to remove.
	plan_remove=" $MISSING_PACKAGE $remove_later "
	[ ! "${plan_remove// }" ] && unset plan_remove
	unset MISSING_PACKAGE remove_later
	rwanted=$(look_for_rwanted)

	for pkg in $(scan $PACKAGE --look_for=bdep --with_dev | \
		fgrep -v $(for i in $(look_for_rwanted) $PACKAGE; do echo " -e $i"; done))
	do

		# Delay the removing of previous cook depends if they are needed
		# for next cook too.
		if [ ! -d "$INSTALLED/$pkg" ] ; then
			MISSING_PACKAGE="$MISSING_PACKAGE $pkg"
		fi
		if [ "$plan_remove" != "${plan_remove/ $pkg }" ]; then
			plan_remove="${plan_remove/ $pkg / }"
			remove_later="$remove_later $pkg"
		fi
		if grep -q ^$pkg$ $PACKAGES_REPOSITORY/broken; then
			broken="$broken$pkg "
		fi
	done
	
	# Don't cook if a depend is broken.
	if [ "$broken" ]; then
		MISSING_PACKAGE=$plan_remove
		echo "Can't cook $PACKAGE because broken depend(s) : $broken" >&2
		unset plan_remove broken
		
		# Set report step to failed.
		report_return_code=1
		report end-step
		return 1
	fi
	if [ "$MISSING_PACKAGE" ]; then
		install_missing()
		{
			echo "Installing missing packages : $MISSING_PACKAGE"
			for pkg in $MISSING_PACKAGE; do
				[ -d "$INSTALLED/$pkg" ] || tazpkg get-install $pkg
			done
		}
		if [ "$auto_install" = yes ]; then
			install_missing
		else
			echo "================================================================================"
			for pkg in $MISSING_PACKAGE
			do
				echo "Missing : $pkg"
			done
			echo "================================================================================"
			echo "You can continue, exit or install missing dependencies."
			echo -n "Install, continue or exit (install/y/N) ? "; read answer
			case $answer in
				install)
					install_missing ;;
				y|yes)
					unset MISSING_PACKAGE;;
				*)
					report stop
					exit 0 ;;
			esac
		fi
	fi
	report end-step
	remove_build_depends $plan_remove
	unset plan_remove
}

remove_build_depends()
{
	[ "$1" ] || return
	report step "Removing previous build dependencies"
	echo "Removing theses packages : $@"
	for pkg in $@; do
		[ -f "$INSTALLED/$pkg/receipt" ] && tazpkg remove $pkg --auto
	done
	cd $PWD
	report end-step
}

# Check if we can use the new way to handle tarball
# or if we keep the previous method by check for
# _pkg=/src= in receipt and reverse-wanted.
check_for_var_modification()
{
	for var in $@; do
		for pkg in $PACKAGE $(look_for_wanted) $(look_for_rwanted); do
			[ -f $WOK/$pkg/receipt ] || continue
			fgrep -q "$var=" $WOK/$pkg/receipt && return 1
		done
	done
	
	# Tweak to make if; then...; fi function working with this one.
	echo -n ""
}

set_src_path()
{
	if check_for_var_modification src _pkg; then
		src=$WOK/${WANTED:-$PACKAGE}/${WANTED:-$PACKAGE}-$VERSION
	else
		tazwok_warning "Use original name or tarball root directory because src/_pkg are defined into the receipt (this is no more needed!)."
		src=$WOK/${WANTED:-$PACKAGE}/${SOURCE:-${WANTED:-$PACKAGE}}-$VERSION
	fi
	stuff=$WOK/$PACKAGE/stuff
	[ "$WANTED" ] && wanted_stuff=$WOK/$WANTED/stuff
}

set_pkg_path()
{
	if [ -d $WOK/${WANTED:-$PACKAGE}/install ] ; then
		_pkg=$WOK/${WANTED:-$PACKAGE}/install
	else
		_pkg=$src/_pkg
	fi
}

# Output $VERSION-$EXTRAVERSION using packages.txt
get_pkg_version()
{
	[ "$PACKAGE" ] || return
	grep -m1 -A1 -sh ^$PACKAGE$ $1/packages.txt | tail -1 | sed 's/ *//'
}

remove_previous_package()
{
	[ "$prev_VERSION" ] || return
	if [ "$VERSION$EXTRAVERSION" != "$prev_VERSION" ]; then
		rm -f $1/$PACKAGE-$prev_VERSION.tazpkg
	fi
	return 0
}

# Check for src tarball and wget if needed.
check_for_tarball()
{
	[ "$WGET_URL" ] || return 0
	look_for_cookopt !unpack && nounpack=yes
	report step "Checking for source tarball: $PACKAGE"
	local repack_src=$repack_src TARBALL=$TARBALL
	if [ "$repack_src" = yes ] && look_for_cookopt !repack_src; then
			repack_src=no
	fi
	if [ "$target" ]; then
		src="$target"
	else
		set_src_path
	fi
	tmp_src=$tmp/tarball-$$
	if [ ! -f "$SOURCES_REPOSITORY/$TARBALL" ] && \
		[ ! -f "$SOURCES_REPOSITORY/${SOURCE:-$PACKAGE}-$VERSION.tar.lzma" ] ; then
		cd $SOURCES_REPOSITORY
		if [ "$SOURCE" ]; then
			alt_url="http://mirror.slitaz.org/sources/packages/${SOURCE:0:1}/$SOURCE-$VERSION.tar.lzma"
			alt_url2="http://mirror.slitaz.org/sources/packages/${SOURCE:0:1}/$TARBALL"
		else
			alt_url="http://mirror.slitaz.org/sources/packages/${PACKAGE:0:1}/$PACKAGE-$VERSION.tar.lzma"
			alt_url2="http://mirror.slitaz.org/sources/packages/${PACKAGE:0:1}/$TARBALL"
		fi
		download $WGET_URL $alt_url $alt_url2 http://mirror.slitaz.org/sources/packages/${file:0:1}/$file
		unset alt_url
		unset alt_url2
		if [ ! -f "$SOURCES_REPOSITORY/$TARBALL" ] && \
			[ ! -f "$SOURCES_REPOSITORY/${SOURCE:-$PACKAGE}-$VERSION.tar.lzma" ] && \
			[ ! -d $tmp_src ]; then
			echo -e "\nDownload failed, exiting. Please check WGET_URL variable.\n" >&2
			report end-step
			return 1
		fi
	fi
	report end-step
	if { [ -f "$SOURCES_REPOSITORY/${SOURCE:-$PACKAGE}-$VERSION.tar.lzma" ] && [ "$nounpack" ] ; } || \
	{ [ -f "$SOURCES_REPOSITORY/$TARBALL" ] && [ "$repack_src" != yes ] && [ "$nounpack" ] ; }; then
		[ -d "$tmp_src" ] && rm -r $tmp_src
		return 0
	fi

	# Untaring source if necessary. We don't need to extract source if
	# the package is built with a wanted source package.
	if [ "$WANTED" ]; then
		[ -d "$tmp_src" ] && rm -r $tmp_src
		return
	fi

	report step "Untaring source tarball"

	# Log process.
	echo "untaring source tarball" >> $LOG

	# If $tmp_src exists, there's already the unpacked tarball into it.
	if ! [ -d $tmp_src ]; then
		mkdir $tmp_src
		if [ -f "$SOURCES_REPOSITORY/${SOURCE:-$PACKAGE}-$VERSION.tar.lzma" ] && [ "$repack_src" = yes ]; then
			lzma d $SOURCES_REPOSITORY/${SOURCE:-$PACKAGE}-$VERSION.tar.lzma -so | \
				tar xf - -C $tmp_src
			repack_src=no
			TARBALL=${SOURCE:-$PACKAGE}-$VERSION.tar.lzma
		elif [ -f "$SOURCES_REPOSITORY/$TARBALL" ]; then
			case "$TARBALL" in
				*zip|*xpi) cd $tmp_src && unzip -o $SOURCES_REPOSITORY/$TARBALL ;;
				*bz2|*tbz|*gem) tar xjf $SOURCES_REPOSITORY/$TARBALL -C $tmp_src;;
				*tar) tar xf $SOURCES_REPOSITORY/$TARBALL -C $tmp_src;;
				*lzma|*lz) unlzma -c $SOURCES_REPOSITORY/$TARBALL | tar xf - -C $tmp_src;;
				*xz) unxz -c $SOURCES_REPOSITORY/$TARBALL | tar xf - -C $tmp_src;;
				*Z|*taz) uncompress -c $SOURCES_REPOSITORY/$TARBALL | tar xf - -C $tmp_src;;
				*gz) tar xzf $SOURCES_REPOSITORY/$TARBALL -C $tmp_src;;
				*rpm) cd $tmp_src && rpm2cpio $SOURCES_REPOSITORY/$TARBALL | cpio -idm --quiet;;

				# It's a plain file or something receipt unpack itself.	
				*)
					mkdir $tmp_src/${SOURCE:-$PACKAGE}-$VERSION
					cp $SOURCES_REPOSITORY/$TARBALL $tmp_src/${src##*/}
				;;

			esac || { report end-step
				rm -f $SOURCES_REPOSITORY/$TARBALL
				rm -r $tmp_src
				return 1
			}
		fi

		# Check if uncompressed tarball is in a root dir or not.
		if [ "$(ls -A $tmp_src | wc -l)" -gt 1 ] || [ -f $(echo $tmp_src/*) ]; then
			if check_for_var_modification src _pkg; then
				mv $tmp_src $tmp_src-1
				mkdir $tmp_src
				mv $tmp_src-1 $tmp_src/${SOURCE:-$PACKAGE}-$VERSION
			else
				mv $tmp_src/* $WOK/$PACKAGE
				repack_src=no
				rm -r $tmp_src
				tazwok_warning "Put all files into $WOK/$PACKAGE; not sure about how to handle this tarball (no root dir)... Please try to remove src/_pkg definition from receipt if you encounter a problem."
			fi
		fi
	fi

	if [ "$repack_src" = yes ]; then
			report step "Repacking sources in .tar.lzma format"
			[ "$TARBALL" ] && rm -f $SOURCES_REPOSITORY/$TARBALL
			TARBALL=${SOURCE:-$PACKAGE}-$VERSION.tar.lzma
			cd $tmp_src
			tar -c * | lzma e $SOURCES_REPOSITORY/$TARBALL -si
	fi

	# Remove previous tarball if no other package needs it. We take care to
	# keep tarball if the same package use it into main repository.
	if [ "$TARBALL" ]; then
		previous_tarball=$(grep ^$PACKAGE:incoming $SOURCES_REPOSITORY/sources.list | cut -f2)
		if [ "$previous_tarball" ]; then
			sed "/^$PACKAGE:incoming/ s/.*/$PACKAGE:incoming\t$TARBALL/" \
				-i $SOURCES_REPOSITORY/sources.list
			grep -q $'\t'$previous_tarball$ $SOURCES_REPOSITORY/sources.list || \
				rm -f $SOURCES_REPOSITORY/$previous_tarball
		else
			echo -e "$PACKAGE:incoming\t$TARBALL" >> $SOURCES_REPOSITORY/sources.list
		fi
	fi

	if [ "$nounpack" ]; then
		[ -d "$tmp_src" ] && rm -r $tmp_src
		report end-step	
		return
	fi
	if [ ! -d "$src" ]|| [ "$target" ]; then
		# Permissions settings.
		chown -R root.root "$tmp_src"
		if [ -d "$src" ]; then
			mkdir -p $src
			for f in $tmp_src/*/*; do
				cp -a $f $src || { report end-step; rm -r $tmp_src; return 1; }
			done
		else
			if ! check_for_var_modification src _pkg && ! [ "$target" ]; then
				src="${src%/*}/$(ls $tmp_src)"
			fi
			mv $(echo $tmp_src/*) "$src" || { report end-step; rm -r $tmp_src; return 1; }
		fi
		rm -r $tmp_src
	else
		[ -d "$tmp_src" ] && rm -r $tmp_src
		echo "There's already something at $src. Abort." >&2
	fi
	report end-step
}

# Log and execute compile_rules function if it exists, to configure and
# make the package if it exists.
check_for_compile_rules()
{
	if grep -q ^compile_rules $RECEIPT; then
		echo "executing compile_rules" >> $LOG
		report step "Executing compile_rules"
		cd $WOK/$PACKAGE
		rm -f /tmp/config.site

		# Free some RAM by cleaning cache if option is enabled.
		freeram=$(free | fgrep '/+ buffers' | tr -s ' ' | cut -f 4 -d ' ')

		# Disable -pipe in CFLAGS/CXXFLAGS if less than 512Mb of free
		# RAM are available.
		if [ "$freeram" -lt 524288 ] && [ "$CFLAGS" != "${CFLAGS/-pipe}" -o \
			"$CXXFLAGS" != "${CXXFLAGS/-pipe}" ]; then
				tazwok_warning "Disabling -pipe compile flag because only ${freeram}b of RAM are available."
				CFLAGS="${CFLAGS/-pipe}"
				CXXFLAGS="${CXXFLAGS/-pipe}"
		fi
		unset freeram

		# Set cook environnement variables.
		[ "$src" ] || set_src_path
		[ "$DESTDIR" ] || DESTDIR="$WOK/$PACKAGE/install"
		[ "$CONFIG_SITE" ] || CONFIG_SITE=/etc/config.site
		export CFLAGS CXXFLAGS MAKEFLAGS DESTDIR BUILD_HOST \
			CONFIG_SITE default_prefix \
			default_datarootdir default_datadir default_localedir \
			default_infodir default_mandir default_build default_host
		local LC_ALL=POSIX LANG=POSIX
		compile_rules

		# Check if config.site has been used.
		# /!\ disabled since it screw the return_code of the step.
		#if [ -f /tmp/config.site ]; then
		#	rm /tmp/config.site
		#else
		#	tazwok_warning "config.site hasn't been used during \
#configuration process."
		#fi
		report end-step
	fi
}

# Check for loop in deps tree. /!\ can be removed
check_for_deps_loop()
{
	local list
	local pkg
	local deps
	pkg=$1
	shift
	[ -n "$1" ] || return
	list=""

	# Filter out already processed deps
	for i in $@; do
		case " $ALL_DEPS" in
		*\ $i\ *);;
		*) list="$list $i";;
		esac
	done
	ALL_DEPS="$ALL_DEPS$list "
	for i in $list; do
		[ -f $i/receipt ] || continue
		deps="$(DEPENDS=""; . $i/receipt; echo $DEPENDS)"
		case " $deps " in
		*\ $pkg\ *) echo -e "$MSG  $i"; MSG="";;
		*) check_for_deps_loop $pkg $deps;;
		esac
	done
}

# Function used by download().
revert_vcs_failure()
{
	cd $SOURCES_REPOSITORY
	rm -r $tmp_src
}

download()
{
	if [ "$COMMAND" = get-src ]; then
		if [ "${DEPENDS/tar}" != "$DEPENDS" ] || [ "${BUILD_DEPENDS/tar}" != "$BUILD_DEPENDS" ]; then
			[ -f $INSTALLED/tar/receipt ] || tazpkg get-install tar --forced
		fi
	fi
	for file in $@; do
		echo "Downloading from ${file#*|}..."
		case "$file" in
			git\|*)
				file=${file#git|}
				[ "$COMMAND" = get-src ] && [ ! -f $INSTALLED/git/receipt ] && tazpkg get-install git --forced
				if [ -f $INSTALLED/git/receipt ]; then
					mkdir $tmp_src
					cd $tmp_src
					if [ "$BRANCH" ]; then
						git clone $file ${src##*/} && cd ${src##*/} && \
							git checkout $BRANCH && rm -rf .git* && break
					else
						git clone $file ${src##*/} && rm -rf ${src##*/}/.git* && break
					fi
					revert_vcs_failure
				else
					tazwok_warning "Needs git to download the source tarball from $file, please add it as build-depend."
					continue
				fi
			;;
			subversion\|*)
				file=${file#subversion|}
				[ "$COMMAND" = get-src ] && [ ! -f $INSTALLED/subversion/receipt ] && tazpkg get-install subversion --forced
				if [ -f $INSTALLED/subversion/receipt ]; then
					mkdir $tmp_src
					cd $tmp_src
					if [ "$BRANCH" ]; then
						echo t | svn co $file -r $BRANCH ${src##*/} && rm -rf ${src##*/}/.svn* && break
					else
						echo t | svn co $file ${src##*/} && rm -rf ${src##*/}/.svn* && break
					fi
					revert_vcs_failure
				else
					tazwok_warning "Needs subversion to download the source tarball from $file, please add it as build-depend."
					continue
				fi
			;;
			mercurial\|*)
				file=${file#mercurial|}
				[ "$COMMAND" = get-src ] && [ ! -f $INSTALLED/mercurial/receipt ] && tazpkg get-install mercurial --forced
				if [ -f $INSTALLED/mercurial/receipt ]; then
					mkdir $tmp_src
					cd $tmp_src
					if [ "$BRANCH" ]; then
						hg clone $file --rev $BRANCH ${src##*/} && rm -rf ${src##*/}/.hg* && break
					else
						hg clone $file ${src##*/} && rm -rf ${src##*/}/.hg* && break
					fi
					revert_vcs_failure
				else
					tazwok_warning "Needs mercurial to download the source tarball from $file, please add it as build-depend."
					continue
				fi
			;;
			https*)
				[ "$COMMAND" = get-src ] && [ ! -f $INSTALLED/wget/receipt ] && tazpkg get-install wget --forced
				if [ -d $INSTALLED/wget ]; then
					if [ "${WGET_URL%$TARBALL}" = "$WGET_URL" ] && [ "$file" = "$WGET_URL" ]; then
						wget -q --no-check-certificate -O $TARBALL $file && break
					else
						wget -q --no-check-certificate $file && break
					fi
				else
					tazwok_warning "Needs wget to download the source tarball from $file, please add it as build-depend."
					continue
				fi
			;;
			http*|ftp*)
				# Handle crappy URL.	
				if [ "$COMMAND" = get-src ]; then
					if [ "${DEPENDS/wget}" != "$DEPENDS" ] || [ "${BUILD_DEPENDS/wget}" != "$BUILD_DEPENDS" ]; then
						[ -f $INSALLED/wget/receipt ] || tazpkg get-install wget --forced
					fi
				fi
				if [ "${WGET_URL%$TARBALL}" = "$WGET_URL" ] && [ "$file" = "$WGET_URL" ]; then
					wget -q -O $TARBALL $file && break
				else
					wget -q $file && break
				fi
			;;
		esac
	done
}

# Regenerate every package that wants a PACKAGE compiled
refresh_packages_from_compile()
{
	# make tazwok genpkg happy
	mkdir $WOK/$PACKAGE/taz

	# Cook rwanted in default or specied order
	genlist=" $(look_for_rwanted | tr '\n' ' ') "
	for i in $(look_for_cookopt genpkg | tac); do
		[ "${genlist/ $i }" = "$genlist" ] && continue
		genlist=" $i${genlist/ $i / }"
	done
	if [ "$genlist" ]; then
		local PACKAGE SOURCE VERSION EXTRAVERSION CATEGORY SHORT_DESC \
		MAINTAINER WEB_SITE WGET_URL DEPENDS BUILD_DEPENDS WANTED \
		PACKED_SIZE UNPACKED_SIZE COOK_OPT PROVIDE CONFIG_FILES TAGS \
		src _pkg DESTDIR CONFIG_SITE RECEIPT LOG stuff wanted_stuff
		for PACKAGE in $genlist; do
			set_common_path
			gen_package
		done
	fi
}

# Copy all generic files (locale, pixmaps, .desktop). We use standard paths,
# so some packages need to copy these files with the receipt and genpkg_rules.
# This function is executed by gen_package when 'tazwok genpkg'.
copy_generic_files()
{
	# In most cases, locales are in $_pkg/usr/share/locale so we copy files
	# using generic variables and $LOCALE from Tazwok config file.
	if [ "$LOCALE"  ]; then
		if [ -d "$_pkg/usr/share/locale" ]; then
			for i in $LOCALE
			do
				if [ -d "$_pkg/usr/share/locale/$i" ]; then
					mkdir -p $fs/usr/share/locale
					cp -a $_pkg/usr/share/locale/$i $fs/usr/share/locale
				fi
			done
		fi
	fi
	
	# Pixmaps (PNG or/and XPM only). Some icons/images can be added through
	# genpkg_rules and generic copy can be disabled with GENERIC_PIXMAPS="no"
	# in pkg receipt.
	if [ "$GENERIC_PIXMAPS" != "no" ]; then
		if [ -d "$_pkg/usr/share/pixmaps" ]; then
			mkdir -p $fs/usr/share/pixmaps
			cp -a $_pkg/usr/share/pixmaps/$PACKAGE.png \
				$fs/usr/share/pixmaps 2>/dev/null
			cp -a $_pkg/usr/share/pixmaps/$PACKAGE.xpm \
				$fs/usr/share/pixmaps 2>/dev/null
		fi
		
		# Custom or homemade PNG pixmap can be in stuff.
		if [ -f "stuff/$PACKAGE.png" ]; then
			mkdir -p $fs/usr/share/pixmaps
			cp -a stuff/$PACKAGE.png $fs/usr/share/pixmaps
		fi
	fi
	
	# Desktop entry (.desktop).
	if [ -d "$_pkg/usr/share/applications" ]; then
		cp -a $_pkg/usr/share/applications $fs/usr/share
	fi
	
	# Homemade desktop file(s) can be in stuff.
	if [ -d "stuff/applications" ]; then
		mkdir -p $fs/usr/share
		cp -a stuff/applications $fs/usr/share
	fi
	if [ -f "stuff/$PACKAGE.desktop" ]; then
		mkdir -p $fs/usr/share/applications
		cp -a stuff/$PACKAGE.desktop $fs/usr/share/applications
	fi
}

# Find and strip : --strip-all (-s) or --strip-debug on static libs.
strip_package()
{
	report step "Executing strip on all files"
	
	# Binaries.
	for dir in $fs/bin $fs/sbin $fs/usr/bin $fs/usr/sbin $fs/usr/games
	do
		if [ -d "$dir" ]; then
			find $dir -type f -exec strip -s '{}' 2>/dev/null \;
		fi
	done
	
	# Libraries.
	find $fs -name "*.so*" -exec strip -s '{}' 2>/dev/null \;
	find $fs -name "*.a" -exec strip --strip-debug '{}' 2>/dev/null \;
	report end-step
}

# Remove .pyc and .pyo files from packages
py_compiled_files_remove()
{
	report step "Removing all .pyc and .pyo files from package ..."
	find $fs -type f -name "*.pyc" -delete 2>/dev/null
	find $fs -type f -name "*.pyo" -delete 2>/dev/null
	report end-step
}

# Check FSH in a slitaz package (Path: /:/usr)
check_fsh()
{
	cd $WOK/$PACKAGE/taz/*/fs
	if ! [ "$(find * -type f)" ]; then
		echo "$PACKAGE fs is empty." >&2
		cd $WOK/$PACKAGE && rm -rf taz
		return 1
	fi
	[ -n "$FSH" ] || FSH="bin boot dev etc home init lib media mnt proc \
root sbin share sys tmp usr var vz usr/bin usr/games usr/include usr/lib \
usr/local usr/sbin usr/share usr/src"
	for i in `ls -d * usr/* 2>/dev/null`
	do
		if ! echo $FSH | fgrep -q $i; then
			echo "Wrong path: /$i" >&2
			error=1
		fi
	done
	if [ "$error" = "1" ]; then
		cat << _EOT_

Package will install files in a non standard directory and won't be generated.
You may have a wrong copy path in genpkg_rules or need to add some options to
configure in compile_rules. Some valid options for SliTaz (Linux FSH):

 --prefix=/usr
 --sysconfdir=/etc
 --libexecdir=/usr/lib/(pkgname)
 --localstatedir=/var
 --mandir=/usr/share/man
 --infodir=/usr/share/info

For more information please read SliTaz docs and run: ./configure --help
================================================================================
$PACKAGE package generation aborted.

_EOT_

		# Dont generate a corrupted package.
		cd $WOK/$PACKAGE && rm -rf taz
		return 1
	fi
	return 0
}

gen_cookmd5()
{
	# md5sum of cooking stuff make tazwok able to check for changes
	# without hg.
	cd $WOK/$PACKAGE
	md5sum receipt > md5
	[ -f description.txt ] && md5sum description.txt >> md5
	if [ -d stuff ]; then
		find stuff | while read file; do
			md5sum $file >> md5
		done
	fi
}

set_pkg_broken()
{
	if ! grep -q ^$PACKAGE$ $PACKAGES_REPOSITORY/broken; then
		echo $PACKAGE >> $PACKAGES_REPOSITORY/broken
	fi

	# Remove pkg from cooklist to avoid re-cook it if no changes happens
	# in the cook stuff.
	sed "/^$PACKAGE$/d" -i $PACKAGES_REPOSITORY/cooklist
	sed "/^$PACKAGE$/d" -i $PACKAGES_REPOSITORY/commit

	gen_cookmd5

	# Return 1 to make report know that's mother-function failed.
	return 1
}

# Create a package tree and build the gziped cpio archive
# to make a SliTaz (.tazpkg) package.
gen_package()
{
	check_root
	check_for_package_on_cmdline
	check_for_receipt
	source_receipt
	
	# May compute VERSION
	if grep -q ^get_version $RECEIPT; then
		get_version
	fi
	check_for_wanted
	cd $WOK/$PACKAGE
	
	# Remove old Tazwok package files.
	[ -d "taz" ] &&	rm -rf taz
	
	# Create the package tree and set useful variables.
	fs=$WOK/$PACKAGE/taz/$PACKAGE-$VERSION/fs
	mkdir -p $fs
	
	# Set $src for standard package and $_pkg variables.
	set_src_path
	set_pkg_path
	
	# Execute genpkg_rules, check package and copy generic files to build
	# the package.
	report step "Building $PACKAGE with the receipt"
	report open-bloc
	if look_for_cookopt !fs; then
		:
	elif grep -q ^genpkg_rules $RECEIPT; then
		
		# Log process.
		echo "executing genpkg_rules" >> $LOG
		report step "Executing genpkg_rules"
		( set -e;  genpkg_rules ) || { set_pkg_broken; report close-bloc; return 1; }
		check_fsh || { set_pkg_broken; report close-bloc; return 1; }
		cd $WOK/$PACKAGE
		report end-step

		# Skip generic files for packages with a WANTED variable
		# (dev and splited pkgs).
		if [ ! "$WANTED" ]; then
			copy_generic_files
		fi
		look_for_cookopt !strip || strip_package
		py_compiled_files_remove
	else
		echo "No package rules to gen $PACKAGE..." >&2
		set_pkg_broken
		report close-bloc
		return 1
	fi
	
	# Copy the receipt and description (if exists) into the binary package tree.
	cd $WOK/$PACKAGE
	report step "Copying the receipt"
	cp receipt taz/$PACKAGE-$VERSION
	report end-step
	if grep -q ^get_version $RECEIPT; then
		report step "Updating version in receipt"
		sed -i "s/^VERSION=.*/VERSION=\"$VERSION\"/" \
			taz/$PACKAGE-$VERSION/receipt
		report end-step
	fi
	if [ -f "description.txt" ]; then
		report step "Copying the description file"
		cp description.txt taz/$PACKAGE-$VERSION
		report end-step
	fi
	
	# Generate md5 of cooking stuff to look for commit later.
	gen_cookmd5
	echo -e "\n# md5sum of cooking stuff :" >> taz/$PACKAGE-$VERSION/receipt
	cat md5 | sed 's/^/# /' >> taz/$PACKAGE-$VERSION/receipt
	
	# Create the files.list by redirecting find output.
	report step "Creating the list of files"
	cd taz/$PACKAGE-$VERSION
  	LAST_FILE=""
  	{ find fs -print; echo; } | while read file; do
		if [ "$LAST_FILE" ]; then
			case "$file" in
			$LAST_FILE/*)
				case "$(ls -ld "$LAST_FILE")" in
				drwxr-xr-x\ *\ root\ *\ root\ *);;
				*) echo ${LAST_FILE#fs};;
				esac;;
			*) echo ${LAST_FILE#fs};;
			esac
		fi
		LAST_FILE="$file"
	done > files.list
	
	# Next, check if something has changed in lib files.
	if fgrep -q '.so' files.list; then
		for rep in $INCOMING_REPOSITORY $PACKAGES_REPOSITORY \
			$([ "$undigest" ] && echo $SLITAZ_DIR/$SLITAZ_VERSION/packages-incoming && \
			echo $SLITAZ_DIR/$SLITAZ_VERSION/packages); do
			prev_VERSION=$(get_pkg_version $rep)
			[ "$prev_VERSION" ] && pkg_file=$rep/$PACKAGE-$prev_VERSION.tazpkg && break
		done
		if [ "$pkg_file" ]; then
			report step "Look for major/minor update in libraries"
			get_pkg_files $pkg_file
			cd $WOK/$PACKAGE/taz/$PACKAGE-$VERSION
			fgrep ".so" files.list | egrep -v "[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*" | \
			while read lib; do
				fgrep -q "$lib" $pkg_files_dir/files.list && continue
				echo "A minor/major update in libraries is detected, planning re-cook of reverse-depends of $PACKAGE."
				for rdep in $(scan $PACKAGE --look_for=rdep | use_wanted); do
					[ "$rdep" = "${WANTED:-$PACKAGE}" ] && continue
					grep -q ^$rdep$ $PACKAGES_REPOSITORY/blocked \
						$PACKAGES_REPOSITORY/cooklist && continue
					echo $rdep >> $PACKAGES_REPOSITORY/cooklist
				done
				regen_cooklist=yes
				break
			done
			rm -r $pkg_files_dir
			unset pkg_file
			report end-step		
   		fi
   	fi
	if [ ! "$EXTRAVERSION" ]; then
		case "$PACKAGE" in
		linux*);;
		*) EXTRAVERSION="$(grep '/lib/modules/.*-slitaz/' files.list |\
			head -1 | sed 's|/lib/modules/\(.*\)-slitaz/.*|_\1|')";;
		esac
	fi
	rm -f $INCOMING_REPOSITORY/$PACKAGE-$VERSION$EXTRAVERSION.tazpkg 2> /dev/null
	report step "Creating md5sum of files"
	while read file; do
		[ -L "fs$file" ] && continue
		[ -f "fs$file" ] || continue
		md5sum "fs$file" | sed 's/  fs/  /'
	done < files.list > md5sum
	report end-step
	UNPACKED_SIZE=$(du -chs fs receipt files.list md5sum description.txt \
		2> /dev/null | awk '{ sz=$1 } END { print sz }')
	
	# Build cpio archives. Find, cpio and gzip the fs, finish by
	# removing the fs tree.
	# Don't log this because compression always output error messages.
	find fs -print | cpio -o -H newc | case "$PACKAGE-$COMPRESSION" in
	tazpkg-lzma)	gzip > fs.cpio.gz;;
	*-lzma)		lzma e fs.cpio.lzma -si;;
	*)		gzip > fs.cpio.gz;;
	esac && rm -rf fs
	PACKED_SIZE=$(du -chs fs.cpio.* receipt files.list md5sum \
		description.txt 2> /dev/null | awk '{ sz=$1 } END { print sz }')
	report step "Updating receipt sizes"
	sed -i '/^PACKED_SIZE/d' receipt
	sed -i '/^UNPACKED_SIZE/d' receipt
	sed -i "s/^PACKAGE=/PACKED_SIZE=\"$PACKED_SIZE\"\nUNPACKED_SIZE=\"$UNPACKED_SIZE\"\nPACKAGE=/" receipt
	sed -i "s/^VERSION=$/VERSION=\"$VERSION\"/" receipt
	report end-step
	if [ "$EXTRAVERSION" ]; then
		report step "Updating receipt EXTRAVERSION"
		sed -i s/^EXTRAVERSION.*$// receipt
		sed -i "s/^VERSION=/EXTRAVERSION=\"$EXTRAVERSION\"\nVERSION=/" receipt
	fi
	prev_VERSION=$(get_pkg_version $INCOMING_REPOSITORY)
	remove_previous_package $INCOMING_REPOSITORY
	report step "Creating full cpio archive"
	find . -print | cpio -o -H newc > $INCOMING_REPOSITORY/$PACKAGE-$VERSION$EXTRAVERSION.tazpkg
	
	# Restore package tree in case we want to browse it.
	report step "Restoring original package tree"
	{ zcat fs.cpio.gz 2> /dev/null || unlzma -c fs.cpio.lzma; } | cpio --quiet -id
	rm fs.cpio.* && cd ..

	# Recook of reverse-depends if package was broken.
	if grep -q "^$PACKAGE$" $PACKAGES_REPOSITORY/broken; then
		report step "Planning re-try a cook of reverse depends" 
		sed "/^$PACKAGE$/d" -i $PACKAGES_REPOSITORY/broken
		for rdep in $(look_for_rdep); do
			grep -q "^$rdep$" $PACKAGES_REPOSITORY/broken || continue
			grep -q "^$rdep$" $PACKAGES_REPOSITORY/cooklist && continue
			echo "Adding $rdep to the cooklist"
			echo $rdep >> $PACKAGES_REPOSITORY/cooklist
			regen_cooklist=t
		done
		report end-step
	fi
	sed "/^$PACKAGE$/d" -i $PACKAGES_REPOSITORY/commit
	sed "/^$PACKAGE$/d" -i $PACKAGES_REPOSITORY/cooklist
	
	# Log process.
	echo "$PACKAGE-$VERSION$EXTRAVERSION.tazpkg (done)" >> $LOG
	report close-bloc
	echo "Package $PACKAGE ($VERSION$EXTRAVERSION) generated."
	echo "Size : `du -sh $INCOMING_REPOSITORY/$PACKAGE-$VERSION$EXTRAVERSION.tazpkg`"
	echo ""
}

########################################################################
# This section contains functions used by several other functions
# bellow.
########################

# Look for receipt/files.list in wok. If they can't be found, get them
# from package. Accept one argument : absolute path to package.
get_pkg_files()
{
	pkg_files_dir=$tmp/$(basename ${1%.tazpkg})
	mkdir -p $pkg_files_dir && \
		cd $pkg_files_dir && \
		cpio --quiet -idm receipt < $1 && \
		cpio --quiet -idm files.list < $1
}

########################################################################
# This section contains functions to generate packages databases.
########################


gen_packages_db()
{
	# pkg_repository can be $PACKAGES_REPOSITORY or $INCOMING_REPOSITORY.
	[ "$pkg_repository" ] || pkg_repository=$PACKAGES_REPOSITORY
	cd $pkg_repository
	report step "Generating packages lists: $pkg_repository"
	report open-bloc
	report step "Removing old files"
	for file in files.list.lzma packages.list packages.txt \
		packages.desc packages.equiv packages.md5; do
		[ -f $file ] && rm $file
	done
	touch files.list
	
	packages_db_start
	unset RECEIPT
	report step "Reading datas from all packages"
	for pkg in $(echo $pkg_repository/*.tazpkg | fgrep -v '*'); do
		get_packages_info
	done
	report end-step
	packages_db_end
	report close-bloc
}

update_packages_db()
{
	[ "$pkg_repository" ] || pkg_repository=$PACKAGES_REPOSITORY
	cd $pkg_repository
	for file in packages.list packages.equiv packages.md5 packages.desc \
		packages.txt; do
		if [ ! -f "$file" ]; then
			gen_packages_db
			return
		fi
	done
	if	[ -f files.list.lzma ]; then
		lzma d files.list.lzma files.list
	else
		gen_packages_db
	fi
	report step "Updating packages lists: $pkg_repository"
	packages_db_start
	
	# Look for removed/update packages.
	for PACKAGE in $(grep ^[0-9,a-z,A-Z] packages.txt); do
		pkg="$pkg_repository/$(grep -m1 ^$PACKAGE- packages.list).tazpkg"
		if ! [ -f "$pkg" ]; then
			erase_package_info
		else
			if [ "$pkg" -nt "packages.list" ]; then
				updated_pkg="$updated_pkg
$PACKAGE $pkg"
			elif [ ! -f $WOK/$PACKAGE/receipt ] && \
				[ "$COMMAND" = check-incoming -o "$pkg_repository" = "$INCOMING_REPOSITORY" ]; then
				erase_package_info
				echo "Removing $PACKAGE from $pkg_repository."	
				rm $pkg
				[ -d $WOK/$PACKAGE ] && rm -r $WOK/$PACKAGE
				sed "/^$PACKAGE\t/d" -i $wan_db $dep_db
				for i in cookorder.txt cooklist commit blocked broken; do
					sed "/^$PACKAGE$/d" -i $PACKAGES_REPOSITORY/$i
				done	
				rm -f $LOCAL_REPOSITORY/log/$PACKAGE.html	
				if [ "$pkg_repository" = "$INCOMING_REPOSITORY" ] && \
				[ "$(sed 1!d $PACKAGES_REPOSITORY/cookorder.txt)" != "#PlanSort" ] ; then
					sed 1i"#PlanSort" -i $PACKAGES_REPOSITORY/cookorder.txt
					regen_cooklist=yes
				else
					echo "$PACKAGE" >> $PACKAGES_REPOSITORY/removed
					sed -n '1,10p' -i $PACKAGES_REPOSITORY/removed
				fi
			fi
		fi
	done
	echo "$updated_pkg" | sed 1d | while read PACKAGE pkg; do
		erase_package_info
		get_packages_info
	done
	unset updated_pkg
	
	# Look for new packages.
	for pkg in $(echo $pkg_repository/*.tazpkg | fgrep -v '*'); do
		if ! fgrep -q "  ${pkg##*/}" $pkg_repository/packages.md5; then
			get_packages_info
		fi
	done
	report end-step
	packages_db_end
}

packages_db_start()
{
	if [ ! -s packages.txt ]; then
			echo "# SliTaz GNU/Linux - Packages list
#
# Packages : unknow
# Date     : $(date +%Y-%m-%d\ \%H:%M:%S)
#
" > packages.txt
	else
		sed -e 's/^# Packages :.*/# Packages : unknow/' \
			-e "s/# Date     :.*/# Date     : $(date +%Y-%m-%d\ \%H:%M:%S)/" \
			-i packages.txt
	fi
	
	# Needed in some case as tazwok define RECEIPT at configuration time
	# in this particular case it can broke the script.
	unset RECEIPT
}

erase_package_info()
{
	cd $pkg_repository
	sed "/^$PACKAGE$/,/^$/d" -i packages.txt
	sed "/^$PACKAGE /d" -i packages.desc
	sed -e "s/=$PACKAGE /= /" -e "s/ $PACKAGE / /" 	-e "s/ $PACKAGE$//" \
		-e "/=$PACKAGE$/d" -e "s/=[0-9,a-z,A-Z]:$PACKAGE /= /" \
		-e "s/ [0-9,a-z,A-Z]:$PACKAGE / /" -e "s/ [0-9,a-z,A-Z]:$PACKAGE$/ /" \
		-e "/=[0-9,a-z,A-Z]:$PACKAGE$/d" \
		-i packages.equiv
	sed "/^$PACKAGE:/d" -i files.list
	sed "/^$(basename ${pkg%.tazpkg})$/d" -i packages.list
	sed "/ $(basename $pkg)$/d" -i packages.md5
}

get_packages_info()
{
	# If there's no taz folder in the wok, extract infos from the
	# package.
	get_pkg_files $pkg
	source_receipt
	echo "Getting datas from $PACKAGE"

	cat >> $pkg_repository/packages.txt << _EOT_
$PACKAGE
    $VERSION$EXTRAVERSION
    $SHORT_DESC
_EOT_
	if [ "$PACKED_SIZE" ]; then
		cat >> $pkg_repository/packages.txt << _EOT_
    $PACKED_SIZE ($UNPACKED_SIZE installed)

_EOT_
	else
		echo "" >> $pkg_repository/packages.txt
	fi

	# Packages.desc is used by Tazpkgbox <tree>.
	echo "$PACKAGE | $VERSION$EXTRAVERSION | $SHORT_DESC | $CATEGORY | $WEB_SITE" >> $pkg_repository/packages.desc

	# Packages.equiv is used by tazpkg install to check depends
	for i in $PROVIDE; do
		DEST=""
		echo $i | fgrep -q : && DEST="${i#*:}:"
		if grep -qs ^${i%:*}= $pkg_repository/packages.equiv; then
			sed -i "s/^${i%:*}=/${i%:*}=$DEST$PACKAGE /" $pkg_repository/packages.equiv
		else
			echo "${i%:*}=$DEST$PACKAGE" >> $pkg_repository/packages.equiv
		fi
	done	

	if [ -f files.list ]; then 
		{ echo "$PACKAGE"; cat files.list; } | awk '
BEGIN { name="" } { if (name == "") name=$0; else printf("%s: %s\n",name,$0); }' >> $pkg_repository/files.list
	fi

	cd .. && rm -r "$pkg_files_dir"

	cd $pkg_repository
	echo $(basename ${pkg%.tazpkg}) >> packages.list
	[ ! "$package_md5" ] && package_md5=$(md5sum $(basename $pkg))
	echo "$package_md5" >> packages.md5
	unset package_md5
}

source_receipt()
{
	unset PACKAGE SOURCE VERSION EXTRAVERSION CATEGORY SHORT_DESC \
		MAINTAINER WEB_SITE WGET_URL DEPENDS BUILD_DEPENDS WANTED \
		PACKED_SIZE UNPACKED_SIZE COOK_OPT PROVIDE CONFIG_FILES TAGS \
		src _pkg DESTDIR CONFIG_SITE BRANCH TARBALL stuff wanted_stuff
	. ${RECEIPT:-$PWD/receipt}
}

packages_db_end()
{
	cd $pkg_repository
	pkgs=$(wc -l packages.list | sed 's/ .*//')
	sed "s/# Packages : .*/# Packages : $pkgs/" -i packages.txt
	
	# If lists was updated it's generally needed to sort them well.
	if ! sort -c packages.list 2> /dev/null; then
		report step "Sorting packages lists"
		for file in packages.list packages.desc packages.equiv; do
			[ -f $file ] || continue
			sort -o $file $file
		done
		report end-step
	fi
	
	# Dont log this because lzma always output error.
	lzma e files.list files.list.lzma
	rm -f files.list
	[ -f packages.equiv ] || touch packages.equiv
}

########################################################################
# This section contains functions to generate wok database.
########################

gen_wok_db()
{
	report step "Generating wok database"
	report open-bloc
	report step "Removing old files"
	for file in $wan_db $dep_db $PACKAGES_REPOSITORY/cookorder.txt; do
		[ -f $file ] && rm $file
	done
	report step "Generating wok-wanted.txt"
	gen_wan_db
	report step "Generating wok-depends.txt"
	for PACKAGE in $(cut -f1 -d '|' $PACKAGES_REPOSITORY/packages.desc \
		$INCOMING_REPOSITORY/packages.desc | sort -u); do
		RECEIPT=$WOK/$PACKAGE/receipt
		if [ -s $RECEIPT ]; then
			source_receipt
			echo -e $PACKAGE"\t "$DEPENDS" \t "$BUILD_DEPENDS' ' >> $dep_db
		fi
	done
	sort_db
	report close-bloc
}

gen_wan_db()
{
	for RECEIPT in $(fgrep -l WANTED $WOK/*/receipt); do
		WANTED=
		source $RECEIPT
		[ "$WANTED" ] || continue
		echo -e $PACKAGE"\t"$WANTED >> $tmp/wan_db
	done
	if ! [ -f $wan_db ] || [ "$(diff -q $tmp/wan_db $wan_db)" ]; then
		mv -f $tmp/wan_db $wan_db
		plan_regen_cookorder=yes
	else
		rm $tmp/wan_db
	fi
}

update_wan_db()
{
	local PACKAGE=$PACKAGE
	for RECEIPT in $(fgrep WANTED $WOK/*/receipt | \
		fgrep $PACKAGE | cut -f1 -d ':'); do
		WANTED=
		source $RECEIPT
		[ "$WANTED" ] || continue
		wan_info=$(echo -e $PACKAGE"\t"$WANTED)
		[ "$wan_info" = "$(grep -m1 ^$PACKAGE$'\t' $wan_db 2>/dev/null)" ] && return
		sed "/^$PACKAGE\t/d" -i $wan_db
		echo "$wan_info" >> $wan_db
		plan_regen_cookorder=yes
		plan_sort_wandb=yes
	done
}

update_dep_db()
{
	dep_info=$(echo -e $PACKAGE"\t "$DEPENDS" \t "$BUILD_DEPENDS' ')
	[ "$dep_info" = "$(grep -m1 ^$PACKAGE$'\t' $dep_db 2>/dev/null)" ] && return
	sed "/^$PACKAGE\t/d" -i $dep_db
	echo "$dep_info" >> $dep_db
	plan_regen_cookorder=yes
	plan_sort_depdb=yes
}

sort_db()
{
	report step "Generating cookorder.txt"
	cat $dep_db | sed 's/ \t / /' | while read PACKAGE BUILD_DEPENDS; do
		grep -q ^$PACKAGE$'\t' $wan_db && continue
		
		# Replace each BUILD_DEPENDS with a WANTED package by it's
		# WANTED package.
		replace_by_wanted()
		{
			for p in $BUILD_DEPENDS; do
				if grep -q ^$p$'\t' $wan_db; then
					echo -n $(grep ^$p$'\t' $wan_db | cut -f 2)' '
				else
					echo -n $p' '
				fi
			done | tr ' ' '\n' | sort -u | sed "/^$PACKAGE$/d" | tr '\n' ' '
		}
		echo -e $PACKAGE"\t $(replace_by_wanted) "
	done > $tmp/db
	while [ -s "$tmp/db" ]; do
		status=start
		for pkg in $(cut -f 1 $tmp/db); do
			 if ! fgrep -q ' '$pkg' ' $tmp/db; then
				echo $pkg >> $tmp/cookorder
				sed -e "/^$pkg\t/d" -e "s/ $pkg / /g" -i $tmp/db
				status=proceed
			fi
		done
		if [ "$status" = start ]; then
			cp -f $tmp/db /tmp/remain-depends.txt
			echo "Can't go further because there's depency(ies) loop(s). The remaining packages will be commentend in the cookorder and will be unbuild in case of major update until the problem is solved." >&2
			for blocked in $(cut -f 1 $tmp/db); do
				echo "$blocked" >> $PACKAGES_REPOSITORY/blocked
			done
			break
		fi
	done
	[ -s $tmp/cookorder ] || touch $tmp/cookorder
	
	# The toolchain packages are moved in first position.
	grep $(for pkg in `scan "$SLITAZ_TOOLCHAIN $SLITAZ_TOOLCHAIN_EXTRA" \
		--look_for=all --with_args`; do echo " -e ^$pkg$"; done) \
		$tmp/cookorder | tac > $PACKAGES_REPOSITORY/cookorder.txt
	for pkg in $(cat $PACKAGES_REPOSITORY/cookorder.txt); do
		sed "/^$pkg$/d" -i $tmp/cookorder
	done

	tac $tmp/cookorder >> $PACKAGES_REPOSITORY/cookorder.txt
	unset plan_regen_cookorder
	report end-step
}

########################################################################
# SCAN CORE
########################
# Include various scan core-functions. It's not intended to be used
# directly : prefer scan wrappers in next section.

look_for_dep()
{
	if [ "$undigest" ] && [ ! -f "$WOK/$PACKAGE/receipt" ]; then
		grep -m1 ^$PACKAGE$'\t' $SLITAZ_DIR/$SLITAZ_VERSION/packages-incoming/wok-depends.txt \
			| cut -f 2
	else
		grep -m1 ^$PACKAGE$'\t' $INCOMING_REPOSITORY/wok-depends.txt | \
			cut -f 2
	fi
}

look_for_bdep()
{
	look_for_all
}

look_for_all()
{
	if [ "$undigest" ] && [ ! -f "$WOK/$PACKAGE/receipt" ]; then
		grep -m1 ^$PACKAGE$'\t' $SLITAZ_DIR/$SLITAZ_VERSION/packages-incoming/wok-depends.txt \
			| cut -f 2,3 | sed 's/ 	 / /'
	else
		grep -m1 ^$PACKAGE$'\t' $INCOMING_REPOSITORY/wok-depends.txt | \
			cut -f 2,3 | sed 's/ 	 / /'
	fi
}

look_for_rdep()
{
	fgrep ' '$PACKAGE' ' $INCOMING_REPOSITORY/wok-depends.txt | cut -f 1
	if [ "$undigest" ]; then
		for rdep in $(fgrep ' '$PACKAGE' ' $SLITAZ_DIR/$SLITAZ_VERSION/packages-incoming/wok-depends.txt | cut -f 1); do
			if [ ! -f "WOK$/$rdep/receipt" ]; then
				echo "$rdep"
			fi
		done
	fi
}

look_for_rbdep()
{
	fgrep ' '$PACKAGE' ' $INCOMING_REPOSITORY/wok-depends.txt | \
		cut -f 1,3 | fgrep ' '$PACKAGE' ' | cut -f 1
	if [ "$undigest" ]; then
		for rdep in $(fgrep ' '$PACKAGE' ' $SLITAZ_DIR/$SLITAZ_VERSION/packages-incoming/wok-depends.txt \
			| cut -f 1,3 | fgrep ' '$PACKAGE' ' | cut -f 1); do
			if [ ! -f "WOK$/$rdep/receipt" ]; then
				echo "$rdep"
			fi
		done
	fi	
}

# Return WANTED if it exists.
look_for_wanted()
{
	if [ "$undigest" ] && [ ! -f "$WOK/$PACKAGE/receipt" ]; then
		grep -m1 ^$PACKAGE$'\t' $SLITAZ_DIR/$SLITAZ_VERSION/packages-incoming/wok-wanted.txt | cut -f 2
	else
		grep -m1 ^$PACKAGE$'\t' $INCOMING_REPOSITORY/wok-wanted.txt | cut -f 2
	fi
}

# Return packages which wants PACKAGE.
look_for_rwanted()
{
	grep $'\t'$PACKAGE$ $INCOMING_REPOSITORY/wok-wanted.txt | cut -f 1
	if [ "$undigest" ]; then
		for rwanted in $(grep $'\t'$PACKAGE$ $SLITAZ_DIR/$SLITAZ_VERSION/packages-incoming/wok-wanted.txt | cut -f 1); do
			if [ ! -f "$WOK/$rwanted/receipt" ]; then
				echo "$rwanted"
			fi
		done
	fi
}

look_for_dev()
{
	WANTED=$(look_for_wanted)
	if [ "$WANTED" ]; then
		if [ "$undigest" ] && [ ! -f "$WOK/$WANTED/receipt" ]; then
			[ -f "$SLITAZ_DIR/$SLITAZ_VERSION/wok/$WANTED-dev/receipt" ] && echo $WANTED-dev
		else
			[ -f "$WOK/$WANTED-dev/receipt" ] && echo $WANTED-dev
		fi
	fi
	if [ "$undigest" ] && [ ! -f "$WOK/$PACKAGE/receipt" ]; then
		[ -f "$SLITAZ_DIR/$SLITAZ_VERSION/wok/$PACKAGE-dev/receipt" ] && echo $PACKAGE-dev
	else
		[ -f "$WOK/$PACKAGE-dev/receipt" ] && echo $PACKAGE-dev
	fi
}

with_dev()
{
	for PACKAGE in $(cat); do
		echo $PACKAGE
		look_for_dev
	done
}

with_wanted()
{
	for PACKAGE in $(cat); do
		echo $PACKAGE
		look_for_wanted
	done
}

use_wanted()
{
for input in $(cat); do
	{ grep ^$input$'\t' $wan_db || echo $input
	} | sed 's/.*\t//'
done
}

########################################################################
# SCAN
########################
# Use wok-wanted.txt and wok-depeds.txt to scan depends.
# Option in command line (must be first arg) :
#   --look_for=bdep/rbdep - Look for depends or reverse depends.
#   --with_dev - Add development packages (*-dev) in the result.
#   --with_wanted - Add package+reverse wanted in the result.
#   --with_args - Include packages in argument in the result.

scan()
{
	# Get packages in argument.
	local PACKAGE=$PACKAGE WANTED=$WANTED pkg_list=
	for arg in $@; do
		[ "$arg" = "${arg#--}" ] || continue
		pkg_list="$pkg_list $arg"
	done

	# Get options.
	[ "$pkg_list" ] || return
	local cooklist= look_for= with_dev= with_wanted= with_args= log_command="$0 $@" \
		get_options_list="look_for with_dev with_wanted with_args cooklist use_wanted"
	get_options
	
	# Cooklist is a special case where we need to modify a little
	# scan behavior
	if [ "$cooklist" ]; then
		gen_wan_db
		look_for=all && with_args=yes && with_dev= && with_wanted=
		filter=use_wanted
		if [ "$COMMAND" = gen-cooklist ]; then
   			for PACKAGE in $pkg_list; do
				grep -q ^$PACKAGE$'\t' $dep_db && continue
				[ -d "$WOK/$p" ] || continue
				check_for_missing
			done
			append_to_dep()
			{
				if ! grep -q ^$PACKAGE$'\t' $dep_db; then
					check_for_missing && echo $PACKAGE >> $tmp/dep
				else
					echo $PACKAGE >> $tmp/dep
				fi
			}
		else
			append_to_dep()
			{
				check_for_commit && echo $PACKAGE >> $tmp/dep
			}
		fi
	else
		append_to_dep()
		{
			echo $PACKAGE >> $tmp/dep
		}
		# If requested packages are not in dep_db, partial generation of this db is needed.
		for PACKAGE in $pkg_list; do
			grep -q ^$PACKAGE$'\t' $dep_db && continue
			[ -d "$WOK/$p" ] || continue	
			plan_check_for_missing=yes	
			check_for_missing
		done
		if [ "$plan_check_for_missing" ]; then
			append_to_dep()
			{
				if ! grep -q ^$PACKAGE$'\t' $dep_db; then
					check_for_missing && echo $PACKAGE >> $tmp/dep
				else
					echo $PACKAGE >> $tmp/dep
				fi
			}
			check_db_status=yes
			unset plan_check_for_missing
		fi
	fi
	
	[ "$with_dev" ] && filter=with_dev
	[ "$with_wanted" ] && filter=with_wanted
	if [ "$filter" ]; then
		pkg_list=$(echo $pkg_list | $filter | sort -u)
		scan_pkg()
		{
			look_for_$look_for | $filter
		}
	else
		scan_pkg()
		{
			look_for_$look_for
		}
	fi
	touch $tmp/dep
	for PACKAGE in $pkg_list; do
		[ "$with_args" ] && append_to_dep
		scan_pkg		
	done  | tr ' ' '\n' | sort -u > $tmp/list
	[ "$look_for" = bdep ] && look_for=dep
	while [ -s $tmp/list ]; do
		PACKAGE=$(sed 1!d $tmp/list)
		sed 1d -i $tmp/list
		append_to_dep
		for pkg in $(scan_pkg); do
			if ! grep -q ^$pkg$ $tmp/list $tmp/dep; then
				echo $pkg >> $tmp/list
			fi
		done
	done
	if [ "$cooklist" ]; then
		mv $tmp/dep $tmp/cooklist
	else
		cat $tmp/dep | sort -u
	fi
	rm -f $tmp/dep $tmp/list
	if [ "$check_db_status" ]; then
		[ "$plan_sort_depdb" ] && sort -o $dep_db $dep_db && unset plan_sort_depdb
		[ "$plan_sort_wandb" ] && sort -o $wan_db $wan_db && unset plan_sort_wandb
		if [ "$plan_regen_cookorder" ] && \
		[ "$(sed 1!d $PACKAGES_REPOSITORY/cookorder.txt)" != "#PlanSort" ]; then
			grep -q "^#" $PACKAGES_REPOSITORY/cookorder.txt || \
			sed 1i"#PlanSort" -i $PACKAGES_REPOSITORY/cookorder.txt
		fi
	fi
}

########################################################################
# This section contains functions to check package repository and
# find which packages to cook.
########################

check_for_missing()
{
	local PACKAGE=$PACKAGE
	if ! check_for_pkg_in_wok; then
		[ "$?" = 2 ] && return 1
		return
	fi
	RECEIPT=$WOK/$PACKAGE/receipt
	source_receipt
	PACKAGE=${WANTED:-$PACKAGE}
	update_wan_db
	for PACKAGE in $(look_for_rwanted) $PACKAGE; do
		RECEIPT=$WOK/$PACKAGE/receipt
		source_receipt
		update_dep_db
	done
}

check_for_commit()
{
	if ! check_for_pkg_in_wok; then
		[ "$?" = 2 ] && return 1
		return
	fi
	for PACKAGE in $(look_for_rwanted) $PACKAGE; do
		RECEIPT=$WOK/$PACKAGE/receipt
		source_receipt

		# We use md5 of cooking stuff in the packaged receipt to check
		# commit. We look consecutively in 3 different locations :
		# - in the wok/PACKAGE/taz/* folder
		# - in the receipt in the package in incoming repository
		# - in the receipt in the package in packages repository
		# If md5sum match, there's no commit.
		check_for_commit_using_md5sum()
		{
			if [ ! -f $WOK/$PACKAGE/md5 ]; then
				sed -n '/# md5sum of cooking stuff :/,$p' receipt | \
					sed -e 1d -e 's/^# //' > $WOK/$PACKAGE/md5
				cd $WOK/$PACKAGE
			fi
		
			if [ -s md5 ]; then					
				if md5sum -cs md5; then
		
				# If md5sum check if ok, check for new/missing files in
				# cooking stuff.
				for file in $([ -f receipt ] && echo receipt; \
						[ -f description.txt ] && echo description.txt; \
						[ -d stuff ] && find stuff); do
						if ! fgrep -q "  $file" md5; then
							set_commited
						fi
					done
				else
					set_commited
				fi
			else
				set_commited
			fi
		}
		set_commited()
		{
			! grep -q ^$PACKAGE$ $PACKAGES_REPOSITORY/commit &&
				echo $PACKAGE >> $PACKAGES_REPOSITORY/commit
			gen_cookmd5
			update_dep_db
		}
		taz_dir=$(echo $WOK/$PACKAGE/taz/$PACKAGE-* | fgrep -v '*')
		if [ -f $WOK/$PACKAGE/md5 ]; then
			cd $WOK/$PACKAGE
			check_for_commit_using_md5sum
		elif [ "$taz_dir" ]; then
			cd $taz_dir
			check_for_commit_using_md5sum
		else
			pkg=$(echo $INCOMING_REPOSITORY/$PACKAGE-$VERSION*.tazpkg | fgrep -v '*')
			[ "$pkg" ] || pkg=$(echo $PACKAGES_REPOSITORY/$PACKAGE-$VERSION*.tazpkg | fgrep -v '*')
			if [ "$pkg" ]; then
				get_pkg_files $pkg
				check_for_commit_using_md5sum
				rm -r $pkg_files_dir
			else
				set_commited
			fi
		fi
	[ "$forced" ] || echo $PACKAGE >> $tmp/checked
	done
	return
}

gen_cook_list()
{
	report step "Scanning wok"
	if [ "$pkg" ]; then
		scan $pkg --cooklist
	else
		scan `cat $cooklist` --cooklist
	fi
	report end-step
	
	[ -s $tmp/checked ] || [ -s $tmp/cooklist ] || return
	
	# Core toolchain should not be cooked unless cook-toolchain is used.
	if ! [ -f /etc/config.site.tmptoolchain ] ; then
		for PACKAGE in $(scan gcc --look_for=all --with_args --with_wanted); do
			grep -q ^$PACKAGE$ $PACKAGES_REPOSITORY/blocked || \
				echo $PACKAGE >> $PACKAGES_REPOSITORY/blocked
		done
	fi

	if [ -s $PACKAGES_REPOSITORY/commit ] && [ "$COMMAND" != gen-cooklist ]; then
		cd $PACKAGES_REPOSITORY
		for PACKAGE in $(cat commit); do
			WANTED="$(look_for_wanted)"
			if [ "$WANTED" ]; then
				grep -q ^$WANTED$ broken cooklist blocked commit && continue
			fi
			grep -q ^$PACKAGE$ blocked cooklist && continue
			echo $PACKAGE >> cooklist
		done
	fi
	sort_cooklist
}

sort_cooklist()
{
	if [ "$(sed 1!d $PACKAGES_REPOSITORY/cookorder.txt)" = "#PlanSort" ]; then
		sed 1d -i $PACKAGES_REPOSITORY/cookorder.txt
		plan_regen_cookorder=yes
	fi
	[ "$plan_sort_depdb" ] && sort -o $dep_db $dep_db && unset plan_sort_depdb
	[ "$plan_regen_cookorder" ] && sort_db
	report step "Generating cooklist"
	if [ -f "$tmp/checked" ]; then
		rm -f $tmp/cooklist
		cat $tmp/checked | while read PACKAGE; do
			grep -q ^$PACKAGE$ $PACKAGES_REPOSITORY/cooklist && \
				echo $PACKAGE >> $tmp/cooklist
		done
	elif ! [ "$COMMAND" = gen-cooklist ]; then
		cat $PACKAGES_REPOSITORY/blocked | while read PACKAGE; do
			sed "/^$PACKAGE/d" -i $tmp/cooklist
		done
	fi
	report end-step
	[ -s $tmp/cooklist ] || return

	report step "Sorting cooklist"
	for PACKAGE in $(cat $tmp/cooklist); do
		WANTED="$(look_for_wanted)"
		[ "$WANTED" ] || continue
		if grep -q ^$WANTED$ $PACKAGES_REPOSITORY/broken $tmp/cooklist; then
			sed "/^$PACKAGE$/d" -i $tmp/cooklist
		elif [ ! -d $WOK/$WANTED/install ]; then
			sed "/^$PACKAGE$/d" -i $tmp/cooklist
			echo $WANTED >> $tmp/cooklist
		fi
	done

	# Use cookorder.txt to sort cooklist.
	if [ -s $tmp/cooklist ]; then
		cat $PACKAGES_REPOSITORY/cookorder.txt | while read PACKAGE; do
			if grep -q ^$PACKAGE$ $tmp/cooklist; then
				sed "/^$PACKAGE$/d" -i $tmp/cooklist
				echo $PACKAGE >> $tmp/cooklist.tmp
			fi
		done

		# Remaining packages in cooklist are thoses without compile_rules.
		# They can be cooked first in any order.
		if [ -f $tmp/cooklist.tmp ]; then
			cat $tmp/cooklist.tmp >> $tmp/cooklist
			rm $tmp/cooklist.tmp
		fi
		
		cat $tmp/cooklist
		[ "$cooklist" = "$PACKAGES_REPOSITORY/cooklist" ] && \
			cat $tmp/cooklist > $cooklist
	fi
	
	report end-step
}

look_for_missing_pkg()
{
	for pkg in $(cat $PACKAGES_REPOSITORY/$1); do
		grep -q ^$pkg$ $INCOMING_REPOSITORY/packages.txt \
			$PACKAGES_REPOSITORY/packages.txt || \
			continue
		echo $pkg
	done
}

check_for_incoming()
{
	report step "Check that all packages were cooked fine"
	[ -s $INCOMING_REPOSITORY/packages.desc ] || {
	echo "No packages in $INCOMING_REPOSITORY."
	report end-step; return; }
	if [ -s $PACKAGES_REPOSITORY/broken ]; then
		missingpkg=$(look_for_missing_pkg broken)
		if [ "$missingpkg" ]; then
			echo "Don't move incoming packages to main repository because theses ones are broken:" >&2
			echo "$missingpkg"
			report end-step	
			return 1
		fi
	fi
	if [ -s $PACKAGES_REPOSITORY/cooklist ]; then
		missingpkg=$(look_for_missing_pkg cooklist)
		if [ "$missingpkg" ]; then
			echo "Don't move incoming packages to main repository because theses ones needs to be cooked:" >&2
			echo "$missingpkg"
			report end-step	
			return 1
		fi
	fi
	incoming_pkgs="$(cut -f 1 -d '|' $INCOMING_REPOSITORY/packages.desc)"
	if ! [ "$forced" ]; then
		cooklist=$PACKAGES_REPOSITORY/cooklist
		pkg="$incoming_pkgs"
		gen_cook_list
		if [ -s $PACKAGES_REPOSITORY/cooklist ]; then
			missingpkg=$(look_for_missing_pkg cooklist)
			if [ "$missingpkg" ]; then
				echo "Don't move incoming packages to main repository because theses ones needs to be cooked:" >&2
				echo "$missingpkg"
				report end-step	
				return 1
			fi
		fi
	fi

	report step "Moving incoming packages to main repository"
	unset EXTRAVERSION
	for PACKAGE in $incoming_pkgs; do
			prev_VERSION=$(get_pkg_version $PACKAGES_REPOSITORY)
			VERSION=$(get_pkg_version $INCOMING_REPOSITORY)
			remove_previous_package $PACKAGES_REPOSITORY
			echo "Moving $PACKAGE..."
			mv -f $INCOMING_REPOSITORY/$PACKAGE-$VERSION.tazpkg $PACKAGES_REPOSITORY
			touch $PACKAGES_REPOSITORY/$PACKAGE-$VERSION.tazpkg
			previous_tarball=$(grep ^$PACKAGE:main $SOURCES_REPOSITORY/sources.list | cut -f2)
			sed -e "/^$PACKAGE:main/d" \
				-e "s/^$PACKAGE:incoming/$PACKAGE:main/" \
				-i $SOURCES_REPOSITORY/sources.list
			if [ "$previous_tarball" ]; then
				grep -q $'\t'$previous_tarball$ $SOURCES_REPOSITORY/sources.list || \
					rm -f $SOURCES_REPOSITORY/$previous_tarball
			fi
	done
	for file in packages.list packages.equiv packages.md5 packages.desc \
		packages.txt; do
		echo -n "" > $INCOMING_REPOSITORY/$file
	done
	rm -r $INCOMING_REPOSITORY/files.list.lzma
	pkg_repository=$PACKAGES_REPOSITORY && update_packages_db

	report step "Updating flavors"
	if [ -x /usr/bin/tazlito ] || [ -x /usr/bin/clean-chroot ]; then
		if ! [ -x /usr/bin/tazlito ]; then
			tazpkg get-install tazlito
		fi

		# Handle cases where tazwok is used into main system;
		# Handle cases where SLITAZ_DIR is not /home/slitaz.
		[ -L /home/slitaz/flavors ] && rm /home/slitaz/flavors
		mkdir -p /home/slitaz
		ln -s $LOCAL_REPOSITORY/flavors /home/slitaz/flavors

		cd $LOCAL_REPOSITORY/packages
		for i in $LOCAL_REPOSITORY/flavors/*; do
			[ -d "$i" ] || continue	
			tazlito pack-flavor ${i##*/}
		done

		noheader=""
		for i in *.flavor; do
			tazlito show-flavor $i --brief $noheader
			noheader="--noheader"
		done > flavors.list
		[ -x /usr/bin/clean-chroot ] && clean-chroot
	else
		echo "Can't create up-to-date flavors because tazlito package is missing." >&2
	fi
	report end-step
}

########################################################################
# TAZWOK MAIN FUNCTIONS
########################

clean()
{
	cd $WOK/$PACKAGE
	ls -A $WOK/$PACKAGE | grep -q -v -e ^receipt$ -e ^description.txt$ \
		-e ^stuff$ || return
	
	[ "$COMMAND" = clean-wok ] || report step "Cleaning $PACKAGE"
	# Check for clean_wok function.
	if grep -q ^clean_wok $RECEIPT; then
		clean_wok
	fi
	# Clean should only have a receipt, stuff and optional desc.
	for f in `ls .`
	do
		case $f in
			receipt|stuff|description.txt|md5)
				continue ;;
			*)
				rm -rf $f ;;
		esac
	done
	[ "$COMMAND" != clean-wok ] && report end-step
}

# Configure and make a package with the receipt.
compile_package()
{
	check_for_package_on_cmdline

	# Include the receipt to get all needed variables and functions
	# and cd into the work directory to start the work.
	check_for_receipt
	source_receipt

	# Log the package name and date.
	echo "date `date +%Y%m%d\ \%H:%M:%S`" >> $LOG
	echo "package $PACKAGE (compile)" >> $LOG

	# Set wanted $src variable to help compiling.
	[ ! "$src" ] && set_src_path
	check_for_build_depends || return 1
	check_for_wanted 
	unset target
	check_for_tarball && check_for_compile_rules
}

# Cook command also include all features to manage lists which keep
# track of wok/packages state.
cook()
{
	cook_code=
	set_common_path
	check_for_receipt
	source_receipt

	# Define log path and start report.
	[ -f $LOCAL_REPOSITORY/log/$PACKAGE.html ] && rm $LOCAL_REPOSITORY/log/$PACKAGE.html
	report sublog $LOCAL_REPOSITORY/log/$PACKAGE.html
	echo "$PACKAGE" > $LOCAL_REPOSITORY/log/package
	report step "Cooking $PACKAGE"
	report open-bloc

	clean $PACKAGE
	[ -s $tmp/cooklist ] && sed "/^$PACKAGE$/d" -i $tmp/cooklist

	if compile_package; then
		remove_src
		refresh_packages_from_compile
		gen_package

		# Update packages-incoming repository.
		store_pkgname=$PACKAGE
		pkg_repository=$INCOMING_REPOSITORY
		update_packages_db

		PACKAGE=$store_pkgname
		unset store_pkgname
		
		# Upgrade to cooked packages if it was previously installed.
		report step "Look for package(s) to upgrade"
		for pkg in $(look_for_rwanted) $PACKAGE; do
			if [ -d $INSTALLED/$pkg ]; then
				tazpkg get-install $pkg --forced
			fi
		done
		report end-step
	else
		set_pkg_broken
		cook_code=1
	fi

	# Remove build_depends in cook mode (if in cooklist, it's done when
	# checking build_depends of next package and we remove only unneeded
	# packages to keep chroot minimal and gain some time).
	if [ "$COMMAND" = cook ]; then
		remove_build_depends $MISSING_PACKAGE
		[ -x /usr/bin/clean-chroot ] && clean-chroot
	fi
	
	# Regen the cooklist if it was planned and command is not cook.
	[ "$regen_cooklist" ] && unset regen_cooklist && \
		[ "$COMMAND" != cook ] && sort_cooklist

	# Some hacks to set the bloc & function status as failed if cook was
	# failed.
	report_return_code=$cook_code
	report close-bloc
	report end-sublog
	rm -f $LOCAL_REPOSITORY/log/package
	return $cook_code
}

cook_list()
{
	if [ -s $tmp/cooklist ]; then
		if [ -f /usr/bin/tazchroot ]; then
			# Note : options -main variables- are automatically keeped by
			# the sub-applications tazchroot/tazwok; as well as report data.
			cd $LOCAL_REPOSITORY
			[ ! -f tazchroot.conf ] && configure_tazchroot
			tazchroot tazwok cook-list --SLITAZ_DIR=$SLITAZ_DIR --SLITAZ_VERSION=$SLITAZ_VERSION ${undigest:+ --undigest=$undigest}
			return
		fi
		while [ -s $tmp/cooklist ]; do
			PACKAGE=$(sed 1!d $tmp/cooklist)
			cook
		done
		remove_build_depends $MISSING_PACKAGE $remove_later
		[ -x /usr/bin/clean-chroot ] && clean-chroot
	else
		echo "Nothing to cook."
		return
	fi
}

configure_tazchroot()
{
	cat > $LOCAL_REPOSITORY/tazchroot.conf << EOF
# Tazchroot configuration file - created by tazwok.

# Default chroot path
SLITAZ_DIR=$SLITAZ_DIR
SLITAZ_VERSION=$SLITAZ_VERSION
$( [ "$undigest" ] && echo "undigest=$undigest" )
LOCAL_REPOSITORY=$SLITAZ_DIR/$(if [ "$undigest" ]; then echo '$undigest'; else echo '$SLITAZ_VERSION'; fi)
chroot_dir=\$LOCAL_REPOSITORY/chroot

# Default scripts path (theses scripts are added in the
# $chroot_dir/usr/bin and can be called with tazchroot script)
script_dir=/usr/lib/slitaz/chroot-scripts/tazwok

# List of directories to mount.
list_dir="$(for dir in packages wok src packages-incoming log flavors iso clean-wok; do echo $LOCAL_REPOSITORY/$dir; done)
$SLITAZ_LOG$( [ "$undigest" ] && echo -e "\n$SLITAZ_DIR/$SLITAZ_VERSION/packages" )"

create_chroot()
{
	mkdir -p \$chroot_dir
	for pkg in \$(tazwok build-depends toolchain --SLITAZ_DIR=\$SLITAZ_DIR --SLITAZ_VERSION=\$SLITAZ_VERSION${undigest:+ --undigest=\$undigest}); do
		tazpkg get-install \$pkg --root="\$chroot_dir"
	done

	# Store list of installed packages needed by cleanchroot.
	ls -1 \$chroot_dir/\$INSTALLED > \$chroot_dir/\$LOCALSTATE/chroot-pkgs

	sed -e "s~^SLITAZ_DIR=.*~SLITAZ_DIR=\$SLITAZ_DIR~" \\
		-e "s/^SLITAZ_VERSION=.*/SLITAZ_VERSION=\$SLITAZ_VERSION/" \\
		-i \$chroot_dir/etc/slitaz/slitaz.conf
$( [ "$undigest" ] && echo '	echo "undigest='"$undigest"'" >> $chroot_dir/etc/slitaz/tazwok.conf')
	sed 's/LC_ALL/LC_ALL=POSIX/' -i \$chroot_dir/etc/profile
	# The build bot may run in a sandbox: link sandbox lockfile
	ln -s \$LOCAL_REPOSITORY/sandbox/proc/1 \$chroot_dir/proc/1
}

mount_chroot()
{
	cp -a /etc/resolv.conf \$chroot_dir/etc/resolv.conf
	echo "\$LOCAL_REPOSITORY/packages" > \$chroot_dir\$LOCALSTATE/mirror
	mkdir -p \$chroot_dir\$LOCALSTATE/undigest/\${LOCAL_REPOSITORY##*/}-incoming
	echo "\$LOCAL_REPOSITORY/packages-incoming" > \$chroot_dir\$LOCALSTATE/undigest/\${LOCAL_REPOSITORY##*/}-incoming/mirror
$( [ "$undigest" ] && echo '	mkdir -p $chroot_dir$LOCALSTATE/undigest/$SLITAZ_VERSION
	echo "$SLITAZ_DIR/$SLITAZ_VERSION/packages" > $chroot_dir$LOCALSTATE/undigest/$SLITAZ_VERSION/mirror' )
	echo -e "\${LOCAL_REPOSITORY##*/}-incoming\nmain" > \$chroot_dir\$LOCALSTATE/priority
	mount -t proc proc \$chroot_dir/proc
	mount -t sysfs sysfs \$chroot_dir/sys
	mount -t devpts devpts \$chroot_dir/dev/pts
	mount -t tmpfs shm \$chroot_dir/dev/shm 
	for dir in \$list_dir; do
		mkdir -p \$dir \$chroot_dir\$dir
		mount \$dir \$chroot_dir\$dir
	done
}

umount_chroot()
{
	for dir in \$list_dir; do
		umount \$chroot_dir\$dir
	done
	umount \$chroot_dir/dev/shm
	umount \$chroot_dir/dev/pts
	umount \$chroot_dir/sys
	umount \$chroot_dir/proc
}
EOF
}

########################################################################
######################### END OF NEW FUNCTIONS #########################
########################################################################

# List packages providing a virtual package
whoprovide()
{
	local i;
	for i in $(fgrep -l PROVIDE $WOK/*/receipt); do
		. $i
		case " $PROVIDE " in
		*\ $1\ *|*\ $1:*) echo $(basename $(dirname $i));;
		esac
	done
}

########################################################################
# TAZWOK COMMANDS
########################

case "$COMMAND" in
	stats)
		# Tazwok general statistics from the wok config file.
		#
		get_tazwok_config
		echo -e "\n\033[1mTazwok configuration statistics\033[0m
================================================================================
Wok directory        : $WOK
Packages repository  : $PACKAGES_REPOSITORY
Incoming repository  : $INCOMING_REPOSITORY
Sources repository   : $SOURCES_REPOSITORY
Log directory        : $LOCAL_REPOSITORY/log
Packages in the wok  : `ls -1 $WOK | wc -l`
Cooked packages      : `ls -1 $PACKAGES_REPOSITORY/*.tazpkg 2>/dev/null | wc -l`
Incoming packages    : `ls -1 $INCOMING_REPOSITORY/*.tazpkg 2>/dev/null | wc -l`
================================================================================\n"
	;;
	edit)
		get_tazwok_config
		check_for_package_on_cmdline
		check_for_receipt
		$EDITOR $WOK/$PACKAGE/receipt
	;;
	build-depends)
		# List dependencies to rebuild wok, or only a package
		get_tazwok_config
		report(){ : ; }
		if [ ! "$PACKAGE" ] || [ "$PACKAGE" = toolchain ]; then
			scan "$SLITAZ_TOOLCHAIN $SLITAZ_TOOLCHAIN_EXTRA" \
				--look_for=dep --with_dev --with_args
		else
			check_for_package_on_cmdline
			scan $PACKAGE --look_for=bdep --with_dev
		fi
	;;
	gen-cooklist)
		check_root
		get_options_list="pkg"
		get_tazwok_config
		report(){ : ; }
		if ! [ "$pkg" ]; then
			if [ ! "$LIST" ] || [ "$LIST" = toolchain ]; then
				pkg="$SLITAZ_TOOLCHAIN $SLITAZ_TOOLCHAIN_EXTRA"
			else
				cooklist=${LIST:-$PACKAGES_REPOSITORY/cooklist}
			fi
		fi
		gen_cook_list
	;;
	check-depends)
		# Check package depends /!\ 
		get_tazwok_config
		echo ""
		echo -e "\033[1mCheck every receipt for DEPENDS - doesn't scan ELF files\033[0m
================================================================================"
		TMPDIR=/tmp/tazwok$$
		DEFAULT_DEPENDS="glibc-base gcc-lib-base"

		# Build ALL_DEPENDS variable
		scan_dep()
		{
			local i
			ALL_DEPENDS="$ALL_DEPENDS$PACKAGE "
			for i in $DEPENDS $SUGGESTED ; do
				case " $ALL_DEPENDS " in
				*\ $i\ *) continue;;
				esac
				[ -d $WOK/$i ] || {
					ALL_DEPENDS="$ALL_DEPENDS$i "
					continue
				}
				DEPENDS=""
				SUGGESTED=""
				. $WOK/$i/receipt
				scan_dep
			done
		}

		# Check for ELF file
		is_elf()
		{
			[ "$(dd if=$1 bs=1 skip=1 count=3 2> /dev/null)" = "ELF" ]
		}

		# Print shared library dependencies
		ldd()
		{
			LD_TRACE_LOADED_OBJECTS=1 /lib/ld*.so $1 2> /dev/null
		}

		mkdir $TMPDIR
		cd $TMPDIR
		for i in $LOCALSTATE/files.list.lzma \
	 		$LOCALSTATE/undigest/*/files.list.lzma ; do
	 		[ -f $i ] && lzma d $i -so >> files.list
		done
		for pkg in $PACKAGES_REPOSITORY/*.tazpkg ; do
			tazpkg extract $pkg > /dev/null 2>&1
			. */receipt
			ALL_DEPENDS="$DEFAULT_DEPENDS "
			scan_dep
			find */fs -type f | while read file ; do
				is_elf $file || continue
				case "$file" in
				*.o|*.ko|*.ko.gz) continue;;
				esac
				ldd $file | while read lib rem; do
					case "$lib" in
					statically|linux-gate.so*|ld-*.so|*/ld-*.so)
						continue;;
					esac
					for dep in $(fgrep $lib files.list | cut -d: -f1); do
						case " $ALL_DEPENDS " in
						*\ $dep\ *) continue 2;;
						esac
						for vdep in $(fgrep $dep $LOCALSTATE/packages.equiv | cut -d= -f1); do
							case " $ALL_DEPENDS " in
							*\ $vdep\ *) continue 3;;
							esac
						done
					done
					[ -n "$dep" ] || dep="UNKNOWN"
					echo "$(basename $pkg): ${file#*fs} depends on package $dep for the shared library $lib"
				done
			done
			rm -rf */
		done
		cd /tmp
		rm -rf $TMPDIR
	;;
	check)
		# Check wok consistency
		get_tazwok_config
		echo ""
		echo -e "\033[1mWok and packages checking\033[0m
================================================================================"
		cd $WOK
		for pkg in $(ls)
		do
			[ -f $pkg/receipt ] || continue
			RECEIPT= $pkg/receipt
			source_receipt
			[ "$PACKAGE" = "$pkg" ] || echo "Package $PACKAGE should be $pkg" >&2
			[ -n "$VERSION" ] || echo "Package $PACKAGE has no VERSION" >&2
			[ -n "$PACKED_SIZE" ] && echo "Package $PACKAGE has hardcoded PACKED_SIZE" >&2
			[ -n "$UNPACKED_SIZE" ] && echo "Package $PACKAGE has hardcoded UNPACKED_SIZE" >&2
			[ -n "$EXTRAVERSION" ] && echo "Package $PACKAGE has hardcoded EXTRAVERSION" >&2
			if [ -n "$WANTED" ]; then
				if [ ! -f $WANTED/receipt ]; then
					echo "Package $PACKAGE wants unknown $WANTED package" >&2
				else
					BASEVERSION=$(. $WANTED/receipt ; echo $VERSION)
					if [ "$VERSION" = "$WANTED" ]; then
						# BASEVERSION is computed in receipt
						fgrep -q '_pkg=' $pkg/receipt &&
						BASEVERSION=$VERSION
					fi
					if [ "$VERSION" != "$BASEVERSION" ]; then
						echo "Package $PACKAGE ($VERSION) wants $WANTED ($BASEVERSION)" >&2
					fi
				fi
			fi

			if [ -n "$CATEGORY" ]; then
				case " $(echo $CATEGORIES) " in
				*\ $CATEGORY\ *);;
				*) echo "Package $PACKAGE has an invalid CATEGORY" >&2;;
				esac
			else
				echo"Package $PACKAGE has no CATEGORY" >&2
			fi
			[ -n "$SHORT_DESC" ] || echo "Package $PACKAGE has no SHORT_DESC" >&2
			[ -n "$MAINTAINER" ] || echo "Package $PACKAGE has no MAINTAINER" >&2
			case "$WGET_URL" in
			ftp*|http*) busybox wget -s $WGET_URL 2> /dev/null ||
				echo "Package $PACKAGE has a wrong WGET_URL" >&2;;
			'') ;;
			*)  echo "Package $PACKAGE has an invalid WGET_URL" >&2;;
			esac
			case "$WEB_SITE" in
			ftp*|http*);;
			'') echo "Package $PACKAGE has no WEB_SITE" >&2;;
			*)  echo "Package $PACKAGE has an invalid WEB_SITE" >&2;;
			esac
			case "$MAINTAINER" in
			*\<*|*\>*) echo "Package $PACKAGE has an invalid MAINTAINER: $MAINTAINER" >&2;;
			esac
			case "$MAINTAINER" in
			*@*);;
			*) echo "Package $PACKAGE MAINTAINER is not an email address" >&2;;
			esac
			MSG="Missing dependencies for $PACKAGE $VERSION$EXTRAVERSION :\n" >&2
			for i in $DEPENDS; do
				[ -d $i ] && continue
				[ -n "$(whoprovide $i)" ] && continue
				echo -e "$MSG  $i"
				MSG=""
			done
			MSG="Missing build dependencies for $PACKAGE $VERSION$EXTRAVERSION :\n" >&2
			for i in $BUILD_DEPENDS; do
				[ -d $i ] && continue
				[ -n "$(whoprovide $i)" ] && continue
				echo -e "$MSG  $i"
				MSG=""
			done
			MSG="Dependencies loop between $PACKAGE and :\n"
			ALL_DEPS=""
			check_for_deps_loop $PACKAGE $DEPENDS
			[ -d $WOK/$pkg/taz ] && for i in $BUILD_DEPENDS; do
				[ $WOK/$pkg/taz -nt $INSTALLED/$i/files.list ] && continue
				echo "$pkg should be rebuilt after $i installation"
			done
		done
	;;
	list)
		# List packages in wok directory. User can specify a category.
		#
		get_tazwok_config
		if [ "$2" = "category" ]; then
			echo -e "\033[1m\nPackages categories :\033[0m $CATEGORIES\n"
			exit 0
		fi
		# Check for an asked category.
		if [ -n "$2" ]; then
			ASKED_CATEGORY=$2
			echo ""
			echo -e "\033[1mPackages in category :\033[0m $ASKED_CATEGORY"
			echo "================================================================================"
			for pkg in $WOK/*
			do
				[ ! -f $pkg/receipt ] && continue
				. $pkg/receipt
				if [ "$CATEGORY" == "$ASKED_CATEGORY" ]; then
					echo -n "$PACKAGE"
					echo -e "\033[28G $VERSION"
					packages=$(($packages+1))
				fi
			done
			echo "================================================================================"
			echo -e "$packages packages in category $ASKED_CATEGORY.\n"
		else
			# By default list all packages and version.
			echo ""
			echo -e "\033[1mList of packages in the wok\033[0m"
			echo "================================================================================"
			for pkg in $WOK/*
			do
				[ ! -f $pkg/receipt ] && continue
				. $pkg/receipt
				echo -n "$PACKAGE"
				echo -en "\033[28G $VERSION"
				echo -e "\033[42G $CATEGORY"
				packages=$(($packages+1))
			done
			echo "================================================================================"
			echo -e "$packages packages available in the wok.\n"
		fi
		;;
	info)
		# Information about a package.
		#
		get_tazwok_config
		check_for_package_on_cmdline
		check_for_receipt
		. $WOK/$PACKAGE/receipt
		echo ""
		echo -e "\033[1mTazwok package information\033[0m
================================================================================
Package	   : $PACKAGE
Version	   : $VERSION
Category   : $CATEGORY
Short desc : $SHORT_DESC
Maintainer : $MAINTAINER"
		if [ ! "$WEB_SITE" = "" ]; then
			echo "Web site   : $WEB_SITE"
		fi
		if [ ! "$DEPENDS" = "" ]; then
			echo "Depends    : $DEPENDS"
		fi
		if [ ! "$WANTED" = "" ]; then
			echo "Wanted src : $WANTED"
		fi
		echo "================================================================================"
		echo ""
	;;
	check-log)
		# We just cat the file log to view process info.
		#
		get_tazwok_config
		if [ ! -f "$LOG" ]; then
			echo -e "\nNo process log found. The package is probably not cooked.\n" >&2
			exit 1
		else
			echo ""
			echo -e "\033[1mPackage process log for :\033[0m $PACKAGE"
			echo "================================================================================"
			cat $LOG
			echo "================================================================================"
			echo ""
			if [ -s "$WOK/$PACKAGE/warning.txt" ]; then
				echo -e "\033[1mCook warning(s) for :\033[0m $PACKAGE"
				echo "================================================================================"
				cat "$WOK/$PACKAGE/warning.txt"
				echo "================================================================================"
				echo ""
			fi
		fi
	;;
	search)
		# Search for a package by pattern or name.
		#
		get_tazwok_config
		if [ -z "$2" ]; then
			echo -e "\nPlease specify a pattern or a package name to search." >&2
			echo -e "Example : 'tazwok search gcc'.\n" >&2
			exit 1
		fi
		echo ""
		echo -e "\033[1mSearch result for :\033[0m $2"
		echo "================================================================================"
		list=`ls -1 $WOK | fgrep $2`
		for pkg in $list
		do
			. $WOK/$pkg/receipt
			echo -n "$PACKAGE "
			echo -en "\033[24G $VERSION"
			echo -e "\033[42G $CATEGORY"
			packages=$(($PACKAGEs+1))
		done
		echo "================================================================================"
		echo "$packages packages found for : $2"
		echo ""
	;;
	compile)
		# Configure and make a package with the receipt.
		#
		get_tazwok_config
		source_lib report
		report start
		compile_package
	;;
	genpkg)
		# Generate a package.
		#
		get_tazwok_config
		source_lib report
		report start
		gen_package
	;;
	cook)
		# Compile and generate a package. Just execute tazwok with
		# the good commands.
		#
		check_root
		get_tazwok_config
		source_lib report
		report start
		update_wan_db
		check_for_commit
		[ "$plan_sort_depdb" ] && sort -o $dep_db $dep_db && unset plan_sort_depdb
		[ "$plan_sort_wandb" ] && sort -o $wan_db $wan_db && unset plan_sort_wandb
		if [ "$plan_regen_cookorder" ]; then
			[ "$(sed 1!d $PACKAGES_REPOSITORY/cookorder.txt)" = "#PlanSort" ] || \
			sed 1i"#PlanSort" -i $PACKAGES_REPOSITORY/cookorder.txt
		fi
		cook
	;;
	sort-cooklist)
		if [ ! -f "$LIST" ]; then
			echo "Usage : tazwok sort-cooklist cooklist" >&2
			exit 1
		fi
		check_root
		get_tazwok_config
		report(){ : ; }
		# When using sort-cooklist, the script should behave as for gen-cooklist
		# The only difference between theses two is where the output is sended.
		COMMAND=gen-cooklist
		cooklist=$LIST
		gen_cook_list
		cp -af $tmp/cooklist $cooklist
	;;
	cook-list)
		# Cook all packages listed in a file or in default cooklist.
		check_root
		get_options_list="pkg forced"
		get_tazwok_config
		source_lib report
		report start
		if ! [ "$pkg" ]; then
			cooklist=${LIST:-$PACKAGES_REPOSITORY/cooklist}
		fi
		gen_cook_list
		cook_list
	;;
	clean)
		# Clean up a package work directory + thoses which want it.
		#
		get_tazwok_config
		check_for_package_on_cmdline
		check_for_receipt
		source_lib report
		report start
		. $RECEIPT
		clean
	;;
	gen-clean-wok)
		# Generate a clean wok from the current wok by copying all receipts
		# and stuff directory.
		#
		get_tazwok_config
		source_lib report
		report start
		if [ -z "$ARG" ]; then
			echo -e "\nPlease specify the destination for the new clean wok.\n" >&2
			exit 1
		else
			dest=$ARG
			mkdir -p $dest
		fi
		report step "Creating clean wok in : $dest"
		for pkg in `ls -1 $WOK`
		do
			mkdir -p $dest/$pkg
			cp -a $WOK/$pkg/receipt $dest/$pkg
			[ -f $WOK/$pkg/description.txt ] && \
				cp -a $WOK/$pkg/description.txt $dest/$pkg
			if [ -d "$WOK/$pkg/stuff" ]; then
				cp -a $WOK/$pkg/stuff $dest/$pkg
			fi
		done
		[ -d $WOK/.hg ] && cp -a $WOK/.hg $dest
		report end-step
		echo "Packages cleaned       : `ls -1 $dest | wc -l`"
		echo ""
	;;
	clean-wok)
		# Clean all packages in the work directory
		#
		get_tazwok_config
		source_lib report
		report start
		report step "Cleaning wok"
		for PACKAGE in `ls -1 $WOK`
		do
			set_common_path
			source_receipt
			clean
		done
		echo "`ls -1 $WOK | wc -l` packages cleaned."
	;;
	clean-src)
		# Remove tarball unrelated to wok receipts from src repo.
		check_root
		get_options_list="forced"
		get_tazwok_config
		cd $SOURCES_REPOSITORY
		echo -n "Checking $SOURCES_REPOSITORY..."	
		for TARBALL in *; do
		[ "$TARBALL" = sources.list ] && continue
		grep -q $'\t'$TARBALL$ $SOURCES_REPOSITORY/sources.list || \
			echo $TARBALL >> $tmp/obsolete
		done
		status
		if ! [ -f $tmp/obsolete ]; then
			echo "No sources need to be removed."
			exit 1
		fi
		echo ""	
		echo -e "\033[1mObsolete/unrelated-to-wok sourcess :\033[0m"
   		horizontal_line
		cat $tmp/obsolete
		horizontal_line
		echo "$(wc -l $tmp/obsolete | cut -f1 -d' ') tarballs to remove."
		echo ""
		echo -n "Please confirm removing (type uppercase YES): "
		read answer
		if [ "$answer" = YES ]; then
			echo -n "Removing old sources..."	
			cat $tmp/obsolete | while read i; do
				rm -f $SOURCES_REPOSITORY/$i
			done
			status
		fi
	;;
	gen-list)
		get_tazwok_config
		if [ "$2" ]; then
			if [ -d "$2" ]; then
				pkg_repository=$2
			else
				echo -e "\nUnable to find directory : $2\n" >&2
				exit 1
			fi
		fi
				
		source_lib report
		report start
		if [ "$pkg_repository" ]; then
			gen_packages_db
		else
			pkg_repository=$PACKAGES_REPOSITORY && gen_packages_db
			pkg_repository=$INCOMING_REPOSITORY && gen_packages_db
		fi
	;;
	check-list)
		# The directory to move into by default is the repository,
		# if $2 is not empty cd into $2.
		#
		get_tazwok_config
		if [ "$2" ]; then
			if [ -d "$2" ]; then
				pkg_repository=$2
			else
				echo -e "\nUnable to find directory : $2\n" >&2
				exit 1
			fi
		fi
		
		source_lib report
		report start
		if [ "$pkg_repository" ]; then
			update_packages_db
		else
			pkg_repository=$PACKAGES_REPOSITORY && update_packages_db
			pkg_repository=$INCOMING_REPOSITORY && update_packages_db
		fi
	;;
	new-tree)
		# Just create a few directories and generate an empty receipt to prepare
		# the creation of a new package.
		#
		get_tazwok_config
		check_for_package_on_cmdline
		clean_wok=$LOCAL_REPOSITORY/clean-wok
		if [ -d $clean_wok/$PACKAGE ]; then
			echo -e "\n$PACKAGE package tree already exists.\n" >&2
			exit 1
		fi
		echo "Creating : $WOK/$PACKAGE"
		mkdir $clean_wok/$PACKAGE
		cd $clean_wok/$PACKAGE
		echo -n "Preparing the receipt..."
		#
		# Default receipt begin.
		#
		echo "# SliTaz package receipt." > receipt
		echo "" >> receipt
		echo "PACKAGE=\"$PACKAGE\"" >> receipt
# Finish the empty receipt.
cat >> receipt << "EOF"
VERSION=""
CATEGORY=""
SHORT_DESC=""
MAINTAINER=""
DEPENDS=""
TARBALL="$PACKAGE-$VERSION.tar.gz"
WEB_SITE=""
WGET_URL=""

# Rules to configure and make the package.
compile_rules()
{
	cd $src
	./configure && make && make install
}

# Rules to gen a SliTaz package suitable for Tazpkg.
genpkg_rules()
{
	mkdir -p $fs/usr
	cp -a $_pkg/usr/bin $fs/usr
}

EOF
#
# Default receipt end.
#
		status
		# Interactive mode, asking and seding.
		if [ "$3" = "--interactive" ]; then
			echo "Entering into interactive mode..."
			echo "================================================================================"
			echo "Package       : $PACKAGE"
			# Version.
			echo -n "Version       : " ; read anser
			sed -i s/'VERSION=\"\"'/"VERSION=\"$anser\""/ receipt
			# Category.
			echo -n "Category      : " ; read anser
			sed -i s/'CATEGORY=\"\"'/"CATEGORY=\"$anser\""/ receipt
			# Short description.
			echo -n "Short desc    : " ; read anser
			sed -i s/'SHORT_DESC=\"\"'/"SHORT_DESC=\"$anser\""/ receipt
			# Maintainer.
			echo -n "Maintainer    : " ; read anser
			sed -i s/'MAINTAINER=\"\"'/"MAINTAINER=\"$anser\""/ receipt
			# Web site.
			echo -n "Web site      : " ; read anser
			sed -i s#'WEB_SITE=\"\"'#"WEB_SITE=\"$anser\""# receipt
			echo ""
			# Wget URL.
			echo "Wget URL to download source tarball."
			echo "Example  : \$GNU_MIRROR/\$PACKAGE/\$TARBALL"
			echo -n "Wget url : " ; read anser
			sed -i s#'WGET_URL=\"\"'#"WGET_URL=\"$anser\""# receipt
			# Ask for a stuff dir.
			echo -n "Do you need a stuff directory ? (y/N) : " ; read anser
			if [ "$anser" = "y" ]; then
				echo -n "Creating the stuff directory..."
				mkdir stuff && status
			fi
			# Ask for a description file.
			echo -n "Are you going to write a description ? (y/N) : " ; read anser
			if [ "$anser" = "y" ]; then
				echo -n "Creating the description.txt file..."
				echo "" > description.txt && status
			fi
			echo "================================================================================"
			echo ""
		fi
	;;
	remove)
		# Remove a package from the wok.
		#
		get_tazwok_config
		check_for_package_on_cmdline
		echo ""
		echo -n "Please confirm deletion (y/N) : "; read anser
		if [ "$anser" = "y" ]; then
			echo -n "Removing $PACKAGE..."
			rm -rf $WOK/$PACKAGE && status
			echo ""
		fi
	;;
	update-wok)
		# Pull and update a Hg wok.
		get_options_list="local"
		get_tazwok_config
		source_lib report
		report start
		clean_wok=$LOCAL_REPOSITORY/clean-wok
		cd $clean_wok
		if ! [ "$local" ]; then
			if [ "$WOK_UPDATE_METHOD" = hg ]; then
				if ! [ -f "$INSTALLED/mercurial/receipt" ]; then

					# Auto-install only if we are in a cook chroot.
					if [ -x /usr/bin/clean-chroot ]; then
						echo "" >&2
						echo "You need to install mercurial to get wok from hg (recommended). Oherwise, you can switch wok get method to \"tarball\" into $LOCAL_RESOSITORY/tazwok.conf (per-repository configuration, it not always exists) or /etc/slitaz/tazwok.conf (global configuration)." | fold -s >&2
						echo "">&2
						exit 1
					else
						tazpkg get-install mercurial
					fi
				fi

				report step "Getting wok changes using hg"
				if [ -d .hg ]; then
					hg pull -u || exit 1
				else
					hg clone $HG_WOK . || exit 1
				fi
				report end-step
				[ -x /usr/bin/clean-chroot ] && clean-chroot
			else
				report step "Getting wok changes using tarball"
				{ mkdir .tmp && cd .tmp
					wget "$TARBALL_WOK" &&
					case $TARBALL_WOK in
						*bz2) tar xjf *.bz2 -C wok; rm *.bz2;;
						*lzma) unlzma -c *.lzma | tar xf - -C wok; rm *.lzma ;;
						*gz) tar xzf *.gz -C wok; rm*.gz ;;
					esac &&
					rm -r $(ls -d $clean_wok/*) &&
					cp -a wok/* $clean_wok &&
					cd .. &&
					rm -r .tmp
				} || { echo "That's not cool: it fails!" >&2
				report end-step
				exit 1; }
				report end-step
			fi
		fi
		report step "Appending changes to wok"

		# Handle removed files/dir.
		cd $WOK	
		for dir in *; do
			[ -d "$clean_wok/$dir" ] || rm -rf $dir
		done
		for file in */receipt */description.txt; do
			[ -f "$clean_wok/$file" ] || rm -rf $file
		done
		for i in $(find */stuff 2>/dev/null); do
			[ -e "$clean_wok/$i" ] || rm -rf $i
		done

		cp -a $clean_wok/* $WOK
		report end-step
	;;
	maintainers)
		get_tazwok_config
		echo ""
		echo "List of maintainers for: $WOK"
		echo "================================================================================"
		touch /tmp/slitaz-maintainers
		for pkg in $WOK/*
		do
			. $pkg/receipt
			if ! fgrep -q "$MAINTAINER" /tmp/slitaz-maintainers; then
				echo "$MAINTAINER" >> /tmp/slitaz-maintainers
				echo "$MAINTAINER"
			fi
		done
		echo "================================================================================"
		echo "Maintainers: `cat /tmp/slitaz-maintainers | wc -l`"
		echo ""
		# Remove tmp files
		rm -f /tmp/slitaz-maintainers
	;;
	maintained-by)
		# Search for packages maintained by a contributor.
		get_tazwok_config
		if [ ! -n "$2" ]; then
			echo "Specify a name or email of a maintainer." >&2
			exit 1
		fi
		echo "Maintainer packages"
		echo "================================================================================"
		for pkg in $WOK/*
		do
			. $pkg/receipt
			if echo "$MAINTAINER" | fgrep -q "$2"; then
				echo "$PACKAGE"
				packages=$(($PACKAGEs+1))
			fi
		done
		echo "================================================================================"
		echo "Packages maintained by $2: $PACKAGEs"
		echo ""
	;;
	tags)
		get_tazwok_config
		echo -e "\n\033[1mTags list :\033[0m"
		horizontal_line
		cd $WOK
		for i in */receipt; do
			unset TAGS
			source $i
			for t in $TAGS; do
				grep -q ^$t$ $tmp/tags && continue
				echo $t | tee -a $tmp/tags
			done
		done
		horizontal_line
		echo "$(wc -l $tmp/tags | cut -f1 -d ' ') tags listed."
	;;		
	check-src)
		# Verify if upstream package is still available
		#
		get_tazwok_config
		check_for_package_on_cmdline
		check_for_receipt
		source_receipt
		check_src()
		{
			for url in $@; do
				busybox wget -s $url  2>/dev/null && break
			done
		}
		if [ "$WGET_URL" ];then
			echo -n "$PACKAGE : "
			check_src $WGET_URL
			status
		else
			echo "No tarball to check for $PACKAGE"
		fi
	;;
	get-src)
		check_root
		get_options_list="target nounpack"
		get_tazwok_config
		check_for_package_on_cmdline
		check_for_receipt
		source_receipt
		if [ "$WGET_URL" ];then
			source_lib report
			report start
			check_for_tarball
		else
			echo "No tarball to download for $PACKAGE"
		fi
	;;
	check-commit)
		check_root
		get_options_list="missing forced"
		get_tazwok_config
		source_lib report
		report start
		if [ "$forced" ]; then
			rm -f $WOK/*/md5
			unset forced
		fi
		if [ "$missing" ]; then
			pkg=$(ls -1 $WOK)
		else
			pkg="$({ grep ^[a-zA-Z0-9] $PACKAGES_REPOSITORY/packages.txt
				grep ^[a-zA-Z0-9] $INCOMING_REPOSITORY/packages.txt
			} | sort -u)"
		fi
		cooklist=$PACKAGES_REPOSITORY/cooklist
		gen_cook_list
	;;
	cook-commit)
		check_root
		get_options_list="missing forced"
		get_tazwok_config
		source_lib report
		report start
		if [ "$forced" ]; then
			rm -f $WOK/*/md5
			unset forced
		fi
		if [ "$missing" ]; then
			pkg=$(ls -1 $WOK)
		else
			pkg="$({ grep ^[a-zA-Z0-9] $PACKAGES_REPOSITORY/packages.txt
				grep ^[a-zA-Z0-9] $INCOMING_REPOSITORY/packages.txt
			} | sort -u)"
		fi
		cooklist=$PACKAGES_REPOSITORY/cooklist
		gen_cook_list
		cook_list
	;;
	cook-all)
		check_root
		get_options_list="forced missing"
		get_tazwok_config
		source_lib report
		report start
		if [ "$missing" ]; then
			pkg=$(ls -1 $WOK)
		else
			pkg="$({ grep ^[a-zA-Z0-9] $PACKAGES_REPOSITORY/packages.txt
				grep ^[a-zA-Z0-9] $INCOMING_REPOSITORY/packages.txt
			} | sort -u)"
		fi
		cooklist=$PACKAGES_REPOSITORY/cooklist
		gen_cook_list
		cook_list
	;;
	gen-wok-db)
		check_root
		get_tazwok_config
		source_lib report
		report start
		gen_wok_db
	;;
	report)
		get_tazwok_config
		cd $PACKAGES_REPOSITORY
		if [ "$2" ]; then
			case $2 in
				commit|cooklist|incoming|broken|blocked)
					show="$2"
				;;
				*)
					echo "usage : tazwok report [commit|cooklist|incoming|broken|blocked]" >&2
					exit 1
				;;
			esac	
		else
			show="commit cooklist incoming broken blocked"
		fi	
		for i in $show; do
			if [ -s $i ]; then
				echo ""	
				echo -e "\033[1m$i\033[0m"
				echo "================================================================================"
				cat $i
				echo "================================================================================"
				echo ""
			fi
		done
	;;
	check-incoming)
		check_root
		get_options_list="forced"
		get_tazwok_config
		source_lib report
		report start
		[ -f $LOCAL_RESOSITORY/incoming ] && rm [ -f $LOCAL_REPOSITORY/incoming ]
		report step "Checking $INCOMING_REPOSITORY"
		report open-bloc
		[ -f $LOCAL_REPOSITORY/log/incoming.html ] && rm $LOCAL_REPOSITORY/log/incoming.html	
		report sublog $LOCAL_REPOSITORY/log/incoming.html
		echo "incoming" > $LOCAL_REPOSITORY/log/package	
		check_for_incoming
		report end-sublog
		report close-bloc
	;;
	configure-chroot)
		check_root
		get_tazwok_config
		if [ -f /usr/bin/tazchroot ]; then
			cd $LOCAL_REPOSITORY
			configure_tazchroot
		else
			echo "The packages tazchroot need to be installed" >&2
			exit 1
		fi
	;;
	chroot)
		check_root
		get_tazwok_config
		# Merge this and the other chroot function ?.
		if [ -f /usr/bin/tazchroot ]; then
			cd $LOCAL_REPOSITORY
			[ ! -f tazchroot.conf ] && configure_tazchroot
			tazchroot
		else
			echo "The packages tazchroot need to be installed" >&2
			exit 1
		fi
	;;
	cook-toolchain)
		check_root
		get_tazwok_config
		echo -n "" > $PACKAGES_REPOSITORY/broken
		if [ -f /usr/bin/tazchroot ]; then
			cd $LOCAL_REPOSITORY
			[ ! -f tazchroot.conf ] && configure_tazchroot
			tazchroot cook-toolchain
			# Buggy : chroot can be elsewhere.
			rm -r $LOCAL_REPOSITORY/chroot
			# /!\ to be writed :
			# next rm chroot and plan cook-all by pushing all packages
			# in cooklist.
		else
			echo "The packages tazchroot need to be installed" >&2
			exit 1
		fi
	;;
	webserver)
		check_root
		get_tazwok_config
		if [ "$ARG" = on ]; then
			if [ "$WEBSERVER" ] && [ -f "$WEBSERVER/repositories.list" ] && \
				grep -q ^"${undigest:-$SLITAZ_VERSION}"$ $WEBSERVER/repositories.list; then
				echo "Webserver is already enabled at $WEBSERVER for ${undigest:-$SLITAZ_VERSION}." >&2
				exit 1
			fi
			if ! [ -f $LOCAL_REPOSITORY/tazchroot.conf ]; then
				tazwok configure-chroot ${undigest:+--undigest=$undigest} --SLITAZ_VERSION=$SLITAZ_VERSION --SLITAZ_DIR=$SLITAZ_DIR
			fi
			for pkg in php lighttpd; do
				[ -d $INSTALLED/$pkg ] || missing="$missing $pkg"
			done
			if [ "$missing" ]; then
				echo "You need to install those packages to start webserver: $missing." >&2
				exit 1
			fi
			if [ ! -f "$LOCAL_REPOSITORY/tazwok.conf" ]; then
				echo "Copying /etc/slitaz/tazwok.conf to $LOCAL_REPOSITORY/tazwok.conf: webserver is configured repository-by-repository."
				cp /etc/slitaz/tazwok.conf $LOCAL_REPOSITORY
			fi
			if ! [ "$WEBSERVER" ]; then
				echo -n "Where to store php pages (default: /var/www/vhosts/bb)? "
				read WEBSERVER
				[ "$WEBSERVER" ] || WEBSERVER="/var/www/vhosts/bb"
			fi
			if [ -f "$WEBSERVER/repositories.list" ] && \
				grep -q ^"${undigest:-$SLITAZ_VERSION}"$ $WEBSERVER/repositories.list; then
				echo "Webserver is already enabled at $WEBSERVER for ${undigest:-$SLITAZ_VERSION}." >&2
				exit 1
			fi
			mkdir -p $WEBSERVER
			echo "${undigest:-$SLITAZ_VERSION}" >> $WEBSERVER/repositories.list
			for file in index.php log.php download.php; do
				[ -f "$WEBSERVER/$file" ] || ln -s /usr/share/slitaz/web-bb/$file $WEBSERVER
			done
			for dir in $PACKAGES_REPOSITORY $INCOMING_REPOSITORY; do
				ln -s $dir $WEBSERVER/${undigest:-$SLITAZ_VERSION}-${dir##*/}
			done
			source $LOCAL_REPOSITORY/tazchroot.conf	
			echo "<?php

// Web interface configuration

\$version=\"${undigest:-$SLITAZ_VERSION}\";
\$chroot=\"$chroot_dir\";
\$lockfile=\"\$chroot/proc/1/status\";
\$db_dir=\"$PACKAGES_REPOSITORY\";
\$log_dir=\"$LOCAL_REPOSITORY/log\";
\$packages=\"$PACKAGES_REPOSITORY\";
\$incoming=\"$INCOMING_REPOSITORY\";
\$wok=\"$WOK\";

?>" > $WEBSERVER/conf-${undigest:-$SLITAZ_VERSION}.php
			[ -L "$WEBSERVER/web" ] || ln -s /usr/share/slitaz/web $WEBSERVER
			echo "WEBSERVER=\"$WEBSERVER\"" >> $LOCAL_REPOSITORY/tazwok.conf
			if [ -L "$WEBSERVER/conf.php" ]; then
				echo "Do yo want to make ${undigest:-$SLITAZ_VERSION} the default page (y/N) ? "
				read answer
				if [ "$answer" = y ]; then
					rm $WEBSERVER/conf.php
					ln -s $WEBSERVER/conf-${undigest:-$SLITAZ_VERSION}.php $WEBSERVER/conf.php
				fi
			else
				ln -s $WEBSERVER/conf-${undigest:-$SLITAZ_VERSION}.php $WEBSERVER/conf.php
			fi
		elif [ "$ARG" = off ]; then
			if ! [ "$WEBSERVER" ]; then
				echo "No webserver running for ${undigest:-$SLITAZ_VERSION}" >&2
				exit 1
			fi
			sed '/^WEBSERVER/d' -i $LOCAL_REPOSITORY/tazwok.conf
			sed "/^${undigest:-$SLITAZ_VERSION}$/d" -i $WEBSERVER/repositories.list
			rm $WEBSERVER/conf-${undigest:-$SLITAZ_VERSION}.php	
			for dir in $PACKAGES_REPOSITORY $INCOMING_REPOSITORY; do
				rm $WEBSERVER/${undigest:-$SLITAZ_VERSION}-${dir##*/}
			done
			if ! [ -s "$WEBSERVER/repositories.list" ]; then
				echo "$WEBSERVER/repositories.list is empty; tazwok doesn't remove the server automatically in case you have important stuff in it. If it's not the case, you can remove it using: rm -r $WEBSERVER"
				rm $WEBSERVER/conf.php	
			elif [ "$(readlink $WEBSERVER/conf.php)" = "$WEBSERVER/conf-${undigest:-$SLITAZ_VERSION}.php" ]; then
				echo "${undigest:-$SLITAZ_VERSION} was the default version to use; switched to : $(sed 1!d $WEBSERVER/repositories.list)"
				rm $WEBSERVER/conf.php
				ln -s $WEBSERVER/conf-$(sed 1!d $WEBSERVER/repositories.list).php $WEBSERVER/conf.php
			fi
		else
			echo "Usage: tazwok webserver on/off" >&2
			exit 1
		fi
	;;
	block)
		# Add a pkg name to the list of blocked packages.
		get_tazwok_config
		check_root
		check_for_package_on_cmdline
		if ! [ -f $WOK/$PACKAGE/receipt ]; then
			echo "Can't find $PACKAGE into wok." >&2
			echo ""	
			exit 1
		fi
		echo ""
		if grep -qs "^$PACKAGE$" $PACKAGES_REPOSITORY/blocked; then
			echo "$PACKAGE is already in the blocked packages list." >&2
			echo ""
			exit 1
		else
			echo -n "Adding $PACKAGE to     : $PACKAGES_REPOSITORY/blocked... "
			echo "$PACKAGE" >> $PACKAGES_REPOSITORY/blocked
			status
			if grep -q "^$PACKAGE$" $PACKAGES_REPOSITORY/cooklist; then
				echo -n "Removing $PACKAGE from : $PACKAGES_REPOSITORY/cooklist... "
				sed -i /"^$PACKAGE$"/d $PACKAGES_REPOSITORY/cooklist
				status
			fi
		fi
		echo "" ;;
	unblock)
		# Remove a pkg name from the list of blocked packages.
		get_tazwok_config
		check_root
		check_for_package_on_cmdline
		if ! [ -f $WOK/$PACKAGE/receipt ]; then
			echo "Can't find $PACKAGE into wok." >&2
			echo ""
			exit 1
		fi
		echo ""
		if grep -qs "^$PACKAGE$" $PACKAGES_REPOSITORY/blocked; then
			echo -n "Removing $PACKAGE from : $PACKAGES_REPOSITORY/blocked... "
			sed -i /"^$PACKAGE$"/d $PACKAGES_REPOSITORY/blocked
			sed -i '/^$/d' $PACKAGES_REPOSITORY/blocked
			status
		else
			echo "$PACKAGE is not in the blocked packages list." >&2
			echo ""
			exit 1
		fi
		echo "" ;;
	usage|*)
		# Print usage also for all unknown commands.
		#
		usage
	;;
esac

report stop 2>/dev/null
exit 0
