#!/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=2.2

####################
# Tazwok variables #
####################

# Packages categories.
CATEGORIES="
base-system
x-window
utilities
network
graphics
multimedia
office
development
system-tools
security
games
misc
meta
non-free"

# Use words rather than numbers in the code.
COMMAND=$1
PACKAGE=$2
LIST=$2

# Include config file or exit if no file found.
if [ -f "./tazwok.conf" ]; then
	. ./tazwok.conf
elif [ -f "/etc/tazwok.conf" ]; then
	. /etc/tazwok.conf
else
	echo -e "\nUnable to find the configuration file : /etc/tazwok.conf"
	echo -e "Please read the Tazwok documentation.\n"
	exit 0
fi

# Create Taz wok needed directories if user is root.
if test $(id -u) = 0 ; then
	# Check for the wok directory.
	if [ ! -d "$WOK" ]; then
		echo "Creating the wok directory..."
		mkdir -p $WOK
		chmod 777 $WOK
	fi
	# Check for the packages repository.
	if [ ! -d "$PACKAGES_REPOSITORY" ]; then
		echo "Creating the packages repository..."
		mkdir -p $PACKAGES_REPOSITORY
	fi
	# Check for the sources repository.
	if [ ! -d "$SOURCES_REPOSITORY" ]; then
		echo "Creating the sources repository..."
		mkdir -p $SOURCES_REPOSITORY
	fi
fi

# The path to the most important file used by Tazwok.
# 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 functions #
####################

# 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.
  build-depends  Generate a list of package to build wok.
  cmp|compare    Compare the wok and the cooked pkgs (--remove old pkgs).
  list           List all packages in the wok tree or by category.
  info           Get information about a package in the wok.
  check          Check every receipt for common errors.
  check-log      Check the process log file of a package.
  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.
  clean          Clean all generated files in the package tree.
  new-tree       Prepare a new package tree and receipt (--interactive).
  gen-list       Generate a packages list for a repository (--text).
  gen-clean-wok  Gen a clean wok in a dir ('clean-wok' cleans current wok).
  remove         Remove a package from the wok.
  hgup           Pull and update a wok under Hg.
  maintainers    List all maintainers in the wok.
  maintained-by  List packages maintained by a contributor\n"
}

# Status function.
status()
{
	local CHECK=$?
	echo -en "\\033[70G[ "
	if [ $CHECK = 0 ]; then
		echo -en "\\033[1;33mOK"
	else
		echo -en "\\033[1;31mFailed"
	fi
	echo -e "\\033[0;39m ]"
}

# Check if user is root.
check_root()
{
	if test $(id -u) != 0 ; then
	   echo -e "\nYou must be root to run `basename $0` with this option."
	   echo -e "Please type 'su' and root password to become super-user.\n"
	   exit 0
	fi
}

# Check for a package name on cmdline.
check_for_package_on_cmdline()
{
	if [ -z "$PACKAGE" ]; then
		echo -e "\nYou must specify a package name on the command line."
		echo -e "Example : tazwok $COMMAND package\n"
		exit 0
	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"
		exit 0
	fi
}

# Check for a specified file list on cmdline.
check_for_list()
{
	if [ -z "$LIST" ]; then
		echo -e "\nPlease specify the path to the list of packages to cook.\n"
		exit 0
	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"
		exit 0
	fi
}

# Check for the wanted package if specified in WANTED
# receipt variable. Set the $src/$_pkg variable to help compiling
# and generating packages.
check_for_wanted()
{
	if [ ! "$WANTED" = "" ]; then
		echo -n "Checking for the wanted package..."
		if [ ! -d "$WOK/$WANTED" ]; then
			echo -e "\nWanted package is missing in the work directory.\n"
			exit 0
		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
				echo -e "\nWanted package source tree is missing in the work directory.\n"
				exit 0
			fi
		fi
		status
		# Set wanted src path.
		src=$WOK/$WANTED/$WANTED-$VERSION
		_pkg=$src/_pkg
	fi
}


# Check for build dependencies, notify user and install if specified.
check_for_build_depends()
{
	echo "Checking for build dependencies..."
	for pkg in $BUILD_DEPENDS
	do
		if [ ! -d "/var/lib/tazpkg/installed/$pkg" ]; then
			MISSING_PACKAGE=$pkg
		fi
	done
	if [ ! "$MISSING_PACKAGE" = "" ]; then
		echo "================================================================================"
		for pkg in $BUILD_DEPENDS
		do
			if [ ! -d "/var/lib/tazpkg/installed/$pkg" ]; then
				MISSING_PACKAGE=$pkg
				echo "Missing : $pkg"
			fi
		done
		echo "================================================================================"
		echo "You can continue, exit or install missing dependencies."
		echo -n "Install, continue or exit (install/y/N) ? "; read anser
		case $anser in
			install)
				for pkg in $BUILD_DEPENDS
				do
					if [ ! -d "/var/lib/tazpkg/installed/$pkg" ]; then
						tazpkg get-install $pkg
					fi
				done ;;
			y|yes)
				continue ;;
			*)
				exit 0 ;;
		esac
	fi
}

# Check for loop in deps tree.
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
}

download()
{
	for file in $@; do
		wget $file && break
	done
}

# 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
	. $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.
	if [ ! "$SOURCE" = "" ]; then
		src=$WOK/$PACKAGE/$SOURCE-$VERSION
	else
		src=$WOK/$PACKAGE/$PACKAGE-$VERSION
	fi
	check_for_build_depends
	check_for_wanted
	echo ""
	echo "Starting to cook $PACKAGE..."
	echo "================================================================================"
	# Check for src tarball and wget if needed.
	if [ ! "$WGET_URL" = "" ]; then
		echo "Checking for source tarball... "
		if [ ! -f "$SOURCES_REPOSITORY/$TARBALL" ]; then
			cd $SOURCES_REPOSITORY
			download $WGET_URL
			#wget $WGET_URL
			# Exit if download failed to avoid errors.
			if [ ! -f "$SOURCES_REPOSITORY/$TARBALL" ]; then
				echo -e "\nDownload failed, exiting. Please check WGET_URL variable.\n"
				exit 1
			fi
		else
			echo -n "Source tarball exit... "
			status
		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
			if [ ! -d $src ]; then
				# Log process.
				echo "untaring $TARBALL" >> $LOG
				echo -n "Untaring $TARBALL... "
				case "$TARBALL" in
				*zip) ( cd $WOK/$PACKAGE; unzip -o $SOURCES_REPOSITORY/$TARBALL );;
				*bz2) tar xjf $SOURCES_REPOSITORY/$TARBALL -C $WOK/$PACKAGE;;
				*tar) tar xf $SOURCES_REPOSITORY/$TARBALL -C $WOK/$PACKAGE;;
				*Z) tar xZf $SOURCES_REPOSITORY/$TARBALL -C $WOK/$PACKAGE;;
				*) tar xzf $SOURCES_REPOSITORY/$TARBALL -C $WOK/$PACKAGE;;
				esac
				status
				# Permissions settings
				chown -R root.root $WOK/$PACKAGE/$PACKAGE-* 2>/dev/null
				chown -R root.root $WOK/$PACKAGE/$SOURCE-* 2>/dev/null
			else
				echo -n "Source direcory exit... " && status
			fi
		fi
	fi
	cd $WOK/$PACKAGE
	# Log and execute compile_rules function if it exists, to configure and
	# make the package if it exists.
	if grep -q ^compile_rules $RECEIPT; then
		echo "executing compile_rules" >> $LOG
		compile_rules
		# Exit if compilation failed so the binary package
		# is not generated when using the cook comand.
		local CHECK=$?
		if [ $CHECK = 0 ]; then
			echo "================================================================================"
			echo "$PACKAGE compiled on : `date +%Y%m%d\ \%H:%M:%S`"
			echo ""
			echo "compilation done : `date +%Y%m%d\ \%H:%M:%S`" >> $LOG
		else
			echo "================================================================================"
			echo "Compilation failed. Please read the compilator output."
			echo "" && exit 1
		fi
	else
		echo "no compile_rules" >> $LOG
		echo -e "No compile rules for $PACKAGE...\n"
	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()
{
	echo -n "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 \;
	status
}

# 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
	EXTRAVERSION=""
	. $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.
	if [ -d "taz" ]; then
		rm -rf taz
	fi
	# Create the package tree and set useful variables.
	mkdir -p taz/$PACKAGE-$VERSION/fs
	fs=taz/$PACKAGE-$VERSION/fs
	# Set $src for standard package and $_pkg variables.
	if [ "$WANTED" = "" ]; then
		src=$WOK/$PACKAGE/$PACKAGE-$VERSION
		_pkg=$src/_pkg
	fi
	if [ ! "$SOURCE" = "" ]; then
		src=$WOK/$PACKAGE/$SOURCE-$VERSION
		_pkg=$src/_pkg
	fi
	cd $WOK/$PACKAGE
	# Execute genpkg_rules and copy generic files to build the package.
	echo ""
	echo "Building $PACKAGE with the receipt..."
	echo "================================================================================"
	if grep -q ^genpkg_rules $RECEIPT; then
		# Log process.
		echo "executing genpkg_rules" >> $LOG
		genpkg_rules
		cd $WOK/$PACKAGE
		# Skip generic files for packages with a WANTED variable 
		# (dev and splited pkgs).
		if [ ! "$WANTED" = "" ]; then
			continue
		else
			copy_generic_files
		fi
		strip_package
	else
		echo "No package rules to gen $PACKAGE..."
		exit 1
	fi
	# Copy the receipt and description (if exists) in the binary package tree.
	cd $WOK/$PACKAGE
	echo -n "Copying the receipt..."
	cp receipt taz/$PACKAGE-$VERSION
	status
	if grep -q ^get_version $RECEIPT; then
		echo -n "Update version in receipt..."
		sed -i "s/^VERSION=.*/VERSION=\"$VERSION\"/" \
			taz/$PACKAGE-$VERSION/receipt
		status
	fi
	if [ -f "description.txt" ]; then
		echo -n "Copying the description file..."
		cp description.txt taz/$PACKAGE-$VERSION
		status
	fi
	# Create the files.list by redirecting find output.
	echo -n "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
	status
	if [ -z "$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 $PACKAGES_REPOSITORY/$PACKAGE-$VERSION$EXTRAVERSION.tazpkg 2> /dev/null
	echo -n "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
	#[ -s md5sum ] || rm -f md5sum
	status
	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.
	echo -n "Compressing the fs... "
	find fs -print | cpio -o -H newc | gzip > fs.cpio.gz && rm -rf fs
	PACKED_SIZE=$(du -chs fs.cpio.gz receipt files.list md5sum \
		description.txt 2> /dev/null | awk '{ sz=$1 } END { print sz }')
	echo -n "Undating receipt sizes..."
	sed -i s/^PACKED_SIZE.*$// receipt	
	sed -i s/^UNPACKED_SIZE.*$// receipt	
	sed -i "s/^PACKAGE=/PACKED_SIZE=\"$PACKED_SIZE\"\nUNPACKED_SIZE=\"$UNPACKED_SIZE\"\nPACKAGE=/" receipt
	sed -i "s/^VERSION=$/VERSION=\"$VERSION\"/" receipt
	status
	if [ -n "$EXTRAVERSION" ]; then
		echo -n "Undating receipt EXTRAVERSION..."
		sed -i s/^EXTRAVERSION.*$// receipt
		sed -i "s/^VERSION=/EXTRAVERSION=\"$EXTRAVERSION\"\nVERSION=/" receipt
		status
	fi
	echo -n "Creating full cpio archive... "
	find . -print | cpio -o -H newc > $PACKAGES_REPOSITORY/$PACKAGE-$VERSION$EXTRAVERSION.tazpkg
	# Restore package tree incase we want to browse it.
	echo -n "Restoring original package tree... "
	zcat fs.cpio.gz | cpio -id
	rm fs.cpio.gz && cd ..
	# Log process.
	echo "$PACKAGE-$VERSION$EXTRAVERSION.tazpkg (done)" >> $LOG
	echo "================================================================================"
	echo "Package $PACKAGE ($VERSION$EXTRAVERSION) generated."
	echo "Size : `du -sh $PACKAGES_REPOSITORY/$PACKAGE-$VERSION$EXTRAVERSION.tazpkg`"
	echo ""
}

# Optional text packages list for gen-list.
gen_textlist()
{
	rm -f packages.desc packages.equiv
	DATE=`date +%Y-%m-%d\ \%H:%M:%S`
	echo -n "Creating the text packages list... "
	cat >> packages.txt << _EOT_
# SliTaz GNU/Linux - Packages list
#
# Packages : _packages_
# Date     : $DATE
#
_EOT_
	for pkg in $WOK/*
	do
	PROVIDE=""
	PACKAGE=""
	PACKED_SIZE=""
	if [ -f $pkg/taz/*/receipt ]; then
		. $pkg/taz/*/receipt
	else
		. $pkg/receipt
	fi
	cat >> packages.txt << _EOT_

$PACKAGE
    $VERSION
    $SHORT_DESC
_EOT_
	if [ -n "$PACKED_SIZE" ]; then
		cat >> packages.txt << _EOT_
    $PACKED_SIZE ($UNPACKED_SIZE installed)	
_EOT_
	fi
	# packages.desc is used by Tazpkgbox <tree>.
	echo "$PACKAGE | $VERSION | $SHORT_DESC | $CATEGORY | $WEB_SITE" >> packages.desc
	# packages.equiv is used by tazpkg install to check depends
	touch packages.equiv
	for i in $PROVIDE; do
		DEST=""
		echo $i | grep -q : && DEST="${i#*:}:"
		if grep -qs ^${i%:*}= packages.equiv; then
			sed -i "s/^${i%:*}=/${i%:*}=$DEST$PACKAGE /" packages.equiv
		else
			echo "${i%:*}=$DEST$PACKAGE" >> packages.equiv
		fi 
	done
	packages=$(($packages+1))
	done && status
	echo -n "Creating the text files list... "
	for pkg in $WOK/*
	do
	if [ -f $pkg/taz/*/files.list ]; then
		. $pkg/taz/*/receipt
		( echo "$PACKAGE"; cat $pkg/taz/*/files.list ) | awk '
BEGIN { name="" } { if (name == "") name=$0; else printf("%s: %s\n",name,$0); }'
	else
		echo "No files_list in $pkg" 1>&2
	fi
	done | lzma e files.list.lzma -si && status
	sed -i s/"_packages_"/"$packages"/ packages.txt
}

# Return the date of the last commit in seconds since Jan 1 1970
hgdate()
{
	local pkg
	local date
	local mon
	# Default date is Jan 1 1970
	[ -d $WOK/.hg -a -x /usr/bin/hg ] || { echo "010100001970"; return; }
	pkg=$(basename $1)
	# Get date for last commit
	date="$( cd $WOK; hg log $(find $pkg/receipt $pkg/stuff -type f \
		2> /dev/null) | grep date: | head -1 | cut -c 6-)"
	[ -n "$date" ] || { echo "010100001970"; return; }
	case "$(echo $date | awk '{ print $2 }')" in
	Jan) mon="01";; Feb) mon="02";; Mar) mon="03";; Apr) mon="04";; 
	May) mon="05";; Jun) mon="06";; Jul) mon="07";; Aug) mon="08";; 
	Sep) mon="09";; Oct) mon="10";; Nov) mon="11";; Dec) mon="12";;
	esac
	# Reformat, don't mind about TZ: we look for days or months delta
	echo $date | sed "s|[^ ]* [^ ]* \\(.*\\) \\(.*\\):\\(.*\\):\\(.*\\) \\(.*\\) .*|$mon\1\2\3\5|"
}

# List packages providing a virtual package
whoprovide()
{
	local i;
	for i in $(grep -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 config file the wok.
		#
		echo ""
		echo -e "\033[1mTazwok configuration statistics\033[0m
================================================================================
Wok directory        : $WOK
Packages repository  : $PACKAGES_REPOSITORY
Sources repository   : $SOURCES_REPOSITORY
Packages in the wok  : `ls -1 $WOK | wc -l`
Cooked packages      : `ls -1 $PACKAGES_REPOSITORY/*.tazpkg 2>/dev/null | wc -l`
================================================================================"
		echo ""
		;;
	build-depends)
		# List dependancies to rebuild wok
		cd $WOK
		ALL_DEPS="slitaz-toolchain"
		echo $ALL_DEPS
		for pkg in $(ls $2)
		do
			[ -f $pkg/receipt ] || continue
			BUILD_DEPENDS=""
			. $pkg/receipt
			for i in $BUILD_DEPENDS; do
				case " $ALL_DEPS " in
				*\ $i\ *);;
				*)	ALL_DEPS="$ALL_DEPS $i"
					echo $i;;
				esac
			done
		done
		;;
	check)
		# Check wok consistancy
		echo ""
		echo -e "\033[1mWok and packages checking\033[0m
================================================================================"
		cd $WOK
		for pkg in $(ls)
		do
			[ -f $pkg/receipt ] || continue
			PACKAGE=""
			VERSION=""
			EXTRAVERSION=""
			CATEGORY=""
			SHORT_DESC=""
			MAINTAINER=""
			WEB_SITE=""
			DEPENDS=""
			BUILD_DEPENDS=""
			WANTED=""
			PACKED_SIZE=""
			UNPACKED_SIZE=""
			. $pkg/receipt
			[ "$PACKAGE" = "$pkg" ] || echo "Package $PACKAGE should be $pkg"
			[ -n "$VERSION" ] || echo "Package $PACKAGE has no VERSION"
			[ -n "$PACKED_SIZE" ] && echo "Package $PACKAGE has hardcoded PACKED_SIZE"
			[ -n "$UNPACKED_SIZE" ] && echo "Package $PACKAGE has hardcoded UNPACKED_SIZE"
			[ -n "$EXTRAVERSION" ] && echo "Package $PACKAGE has hardcoded EXTRAVERSION"
			if [ -n "$WANTED" ]; then
				if [ ! -f $WANTED/receipt ]; then
					echo "Package $PACKAGE want unknown $WANTED package"
				else
					BASEVERSION=$(. $WANTED/receipt ; echo $VERSION)
					if [ "$VERSION" = "$WANTED" ]; then
						# BASEVERSION is computed in receipt
						grep -q '_pkg=' $pkg/receipt && 
						BASEVERSION=$VERSION
					fi
					if [ "$VERSION" != "$BASEVERSION" ]; then
						echo "Package $PACKAGE ($VERSION) want $WANTED ($BASEVERSION)"
					fi
				fi
			fi

			if [ -n "$CATEGORY" ]; then
				case " $(echo $CATEGORIES) " in
				*\ $CATEGORY\ *);;
				*) echo "Package $PACKAGE has an invalid CATEGORY";;
				esac
			else
				echo"Package $PACKAGE has no CATEGORY"
			fi
			[ -n "$SHORT_DESC" ] || echo "Package $PACKAGE has no SHORT_DESC"
			[ -n "$MAINTAINER" ] || echo "Package $PACKAGE has no MAINTAINER"
			case "$WEB_SITE" in
			ftp*|http*);;
			'') echo "Package $PACKAGE has no WEB_SITE";;
			*)  echo "Package $PACKAGE has an invalid WEB_SITE";;
			esac
			case "$MAINTAINER" in
			*\<*|*\>*) echo "Package $PACKAGE has an invalid MAINTAINER: $MAINTAINER";;
			esac
			case "$MAINTAINER" in
			*@*);;
			*) echo "Package $PACKAGE MAINTAINER is not an email address";;
			esac
			MSG="Missing dependencies for $PACKAGE $VERSION$EXTRAVERSION :\n"
			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"
			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
		done
		;;
	cmp|compare)
		# Compare the wok and packages repository to help with maintaining 
		# a mirror.
		echo ""
		echo -e "\033[1mWok and packages comparison\033[0m
================================================================================"
		for pkg in $WOK/*
		do
			WANTED=""
			. $pkg/receipt
			echo "$PACKAGE-$VERSION.tazpkg" >> /tmp/wok.list.$$
			tpkg="$(ls $PACKAGES_REPOSITORY/$PACKAGE-$VERSION*.tazpkg 2> /dev/null | head -1)"
			if [ -z "$tpkg" ]; then
				echo "Missing package: $PACKAGE ($VERSION)"
				echo "$PACKAGE" >> /tmp/pkgs.missing.$$
			elif [ -f $pkg/taz/*/receipt -a ! -f $pkg/taz/*/md5sum ]; then
				echo "Obsolete package: $PACKAGE ($VERSION)"
				echo "$PACKAGE" >> /tmp/pkgs.missing.$$
			elif [ $pkg/receipt -nt $tpkg ]; then
				echo "Refresh package: $PACKAGE ($VERSION)"
				echo "$PACKAGE" >> /tmp/pkgs.missing.$$
			else
				srcdate=$(hgdate $pkg)
				pkgdate=$(date -u -r $tpkg '+%m%d%H%M%Y')
				if [ $(date -d $pkgdate +%s) -lt $(date -d $srcdate +%s) ]; then
					echo "Rebuild package: $PACKAGE ($VERSION) cooked $(date -d $pkgdate "+%x %X"), modified $(date -d $srcdate "+%x %X")"
					echo "$PACKAGE" >> /tmp/pkgs.missing.$$
				else
					continue
				fi
			fi
			if [ "$2" = "--cook" ]; then
				if [ -n "$WANTED" -a ! -d $WOK/$WANTED/taz ]; then
					yes '' | tazwok cook $WANTED
				fi
				yes '' | tazwok cook $PACKAGE
			fi
		done
		for pkg in `cd $PACKAGES_REPOSITORY && ls *.tazpkg`
		do
			# grep $pkg in /tmp/wok.list.$$
			# may include EXTRAVERSION or computed VERSION
			for i in $(grep ^${pkg%-*} /tmp/wok.list.$$); do
				case "$pkg" in
				${i%.tazpkg}*.tazpkg) continue 2;;
				esac
			done
			# Not found
			echo $pkg >> /tmp/pkgs.old.$$
			if [ "$2" = "--remove" ]; then
				echo "Removing package: $pkg"
				rm $PACKAGES_REPOSITORY/$pkg
			else
				echo "Old package:     $pkg"
			fi	
		done
		cd /tmp
		echo "================================================================================"
		echo "Wok: `cat wok.list.$$ | wc -l` - \
Cooked: `ls -1 $PACKAGES_REPOSITORY/*.tazpkg 2>/dev/null | wc -l` - \
Missing: `cat pkgs.missing.$$ 2>/dev/null | wc -l` - \
Old: `cat pkgs.old.$$ 2>/dev/null | wc -l`"
		echo ""
		rm -f wok.list.$$ pkgs.old.$$ pkgs.missing.$$
		;;
	list)
		# List packages in wok directory. User can specifiy a category
		#
		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
				. $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
				. $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.
		#
		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.
		#
		if [ ! -f "$LOG" ]; then
			echo -e "\nNo process log found. The package is probably not cooked.\n"
			exit 0
		else
			echo ""
			echo -e "\033[1mPackage process log for :\033[0m $PACKAGE"
			echo "================================================================================"
			cat $LOG
			echo "================================================================================"
			echo ""
		fi
		;;
	search)
		# Search for a package by pattern or name.
		#
		if [ -z "$2" ]; then
			echo -e "\nPlease specify a pattern or a package name to search."
			echo -e "Example : 'tazwok search gcc'.\n"
			exit 0
		fi
		echo ""
		echo -e "\033[1mSearch result for :\033[0m $2"
		echo "================================================================================"
		list=`ls -1 $WOK | grep $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.
		#
		compile_package
		;;
	genpkg)
		# Generate a package
		#
		gen_package
		;;
	cook)
		# Compile and generate a package. Just execute tazwok with
		# the good commands.
		#
		check_root
		compile_package
		gen_package
		;;
	cook-list)
		# Cook all packages listed in a file. The path to the cooklist must
		# be specified on the cmdline.
		#
		check_root
		check_for_list
		for pkg in $LIST
		do
			tazwok compile $pkg
			tazwok genpkg $pkg
		done
		;;
	clean)
		# Clean up a package work directory.
		#
		check_for_package_on_cmdline
		check_for_receipt
		. $RECEIPT
		cd $WOK/$PACKAGE
		echo ""
		echo "Cleaning $PACKAGE..."
		echo "================================================================================"
		# Check for clean_wok function.
		if grep -q ^clean_wok $RECEIPT; then
			clean_wok
		fi
		# Remove taz/ and source tree if exists.
		if [ -d "taz" ]; then
			echo -n "Removing taz files..."
			rm -rf taz
			status
		fi
		for i in $PACKAGE-$VERSION $SOURCE-$VERSION ; do
			[ -e "$i" ] || continue
			echo -n "Removing source files..."
			if [ -L $i ]; then
				target=$(readlink $i)
				[ -d "$target" ] && case "$target" in
				/*|.|./*|..|../*);;
				*) rm -rf $target;;
				esac
			fi
			rm -rf $i
			status
		done
		# Remove an envental $PACKAGE-build directory.
		if [ -d "$PACKAGE-build" ]; then
			echo -n "Removing build tree..."
			rm -rf $PACKAGE-build && status
		fi
		# Remove process log file.
		if [ -f "process.log" ]; then
			echo -n "Removing process log file..."
			rm process.log && status
			echo "================================================================================"
		fi
		echo "$PACKAGE is clean. You can cook it again..."
		echo ""
		;;
	gen-clean-wok)
		# Generate a clean wok from the current wok by copying all receipt
		# and stuff directory.
		#
		if [ -z "$2" ]; then
			echo -e "\nPlease specify the destination for the new clean wok.\n"
			exit 0
		else
			dest=$2
			mkdir -p $dest
		fi
		echo "New wok is going to : $dest"
		for pkg in `ls -1 $WOK`
		do
			echo "----"
			echo -n "Preparing $pkg..."
			mkdir -p $dest/$pkg
			status
			echo -n "Copying the receipt..."
			cp -a $WOK/$pkg/receipt $dest/$pkg
			status
			if [ -d "$WOK/$pkg/stuff" ]; then
				echo -n "Copying all the stuff directory..."
				cp -a $WOK/$pkg/stuff $dest/$pkg
				status
			fi
		done
		echo "================================================================================"
		echo "Clean wok generated in : $dest"
		echo "Packages cleaned       : `ls -1 $dest | wc -l`"
		echo ""
		;;
	clean-wok)
		# Clean all packages in the work directory
		#
		for pkg in `ls -1 $WOK`
		do
			tazwok clean $pkg
		done
		echo "================================================================================"
		echo "`ls -1 $WOK | wc -l` packages cleaned."
		echo ""
		;;
	gen-list)
		# Sed is used to remove all the .tazpkg extensions from the
		# packages.list. The directory to move in by default is the repository
		# if $2 is not empty cd into $2. A text packages list can also be gen
		# with the option --text.
		#
		fakewok=""
		if [ "$2" == "--text" ]; then
			textlist="yes"
			if [ "$3" == "--fakewok" ]; then
				WOK=/tmp/fakewok-$$
				fakewok="$WOK"
				mkdir -p $WOK
				for i in $PACKAGES_REPOSITORY/*.tazpkg; do
					(cd $WOK; cpio -i receipt files.list 2>/dev/null) < $i
					. $WOK/receipt
					mkdir -p $WOK/$PACKAGE/taz/$PACKAGE-$VERSION
					mv $WOK/receipt $WOK/files.list \
						$WOK/$PACKAGE/taz/$PACKAGE-$VERSION
					ln $WOK/$PACKAGE/taz/$PACKAGE-$VERSION/receipt $WOK/$PACKAGE
				done
			fi
		elif [ -z "$2" ]; then
			PACKAGES_REPOSITORY=$PACKAGES_REPOSITORY
		else
			if [ -d "$2" ]; then
				PACKAGES_REPOSITORY=$2
			else
				echo -e "\nUnable to find directory : $2\n"
				exit 0
			fi
		fi
		cd $PACKAGES_REPOSITORY
		# Remove old packages.list and md5sum, they will soon be rebuilt.
		rm -f packages.list packages.md5 packages.txt
		echo ""
		echo -e "\033[1mGenerating packages lists\033[0m"
		echo "================================================================================"
		echo -n "Repository path : $PACKAGES_REPOSITORY" && status
		# Generate packages.txt
		if [ "$textlist" == "yes" ]; then
			gen_textlist
			[ "$fakewok" == "" ] || rm -rf $fakewok
		fi
		echo -n "Creating the raw packages list... "
		ls -1 *.tazpkg > /tmp/packages.list
		sed -i s/'.tazpkg'/''/ /tmp/packages.list
		status
		echo -n "Building the md5sum for all packages... "
		md5sum *.tazpkg > packages.md5
		status
		mv /tmp/packages.list $PACKAGES_REPOSITORY
		echo "================================================================================"
		pkgs=`cat $PACKAGES_REPOSITORY/packages.list | wc -l`
		echo "$pkgs packages in the repository."
		echo ""
		;;
	new-tree)
		# Just create a few directories and generate an empty receipt to prepare
		# the creation of a new package.
		#
		check_for_package_on_cmdline
		if [ -d $WOK/$PACKAGE ]; then
			echo -e "\n$PACKAGE package tree already exists.\n"
			exit 0
		fi
		echo "Creating : $WOK/$PACKAGE"
		mkdir $WOK/$PACKAGE
		cd $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 \
		--prefix=/usr \
		--infodir=/usr/share/info \
		--mandir=/usr/share/man \
		$CONFIGURE_ARGS &&
	make && make DESTDIR=$PWD/_pkg 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 in 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.
		#
		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
		;;
	hgup)
		# Pull and update an Hg wok.
		if ls -l $WOK/.hg/hgrc | grep -q "root"; then
			check_root
		fi
		cd $WOK
		hg pull && hg update ;;
	maintainers)
		echo ""
		echo "List of maintainers for: $WOK"
		echo "================================================================================"
		touch /tmp/slitaz-maintainers
		for pkg in $WOK/*
		do
			. $pkg/receipt
			if ! grep -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 packagers.
		if [ ! -n "$2" ]; then
			echo "Specify a name or mail of a maintainer."
			exit 0
		fi
		echo "Maintainer packages"
		echo "================================================================================"
		for pkg in $WOK/*
		do
			. $pkg/receipt
			if echo "$MAINTAINER" | grep -q "$2"; then
				echo "$PACKAGE"
				packages=$(($packages+1))
			fi
		done
		echo "================================================================================"
		echo "Packages maintained by $1: $packages"
		echo "" ;;
	usage|*)
		# Print usage also for all unknown commands.
		#
		usage
		;;
esac

exit 0
