#!/bin/sh
#
# Cook - A tool to cook and generate SliTaz packages. Read the README
# before adding or modifying any code in cook!
#
# Copyright (C) SliTaz GNU/Linux - GNU gpl v3
# Author: Christophe Lincoln <pankso@slitaz.org>
#
. /usr/lib/slitaz/libcook.sh

VERSION="3.2"

# Internationalization.
. /usr/bin/gettext.sh
TEXTDOMAIN='cook'
export TEXTDOMAIN

_()  echo -e "$(eval_gettext "$1")"
_n() echo -en "$(eval_gettext "$1")"
# to disable i18n:
# _()  echo -e "$1"
# _n() echo -en "$1"


#
# Functions
#

usage() {
	cat << EOT

$(_ "\033[1mUsage:\033[0m cook [package|command] [list|--option]")

$(_ "\033[1mCommands:\033[0m")
  usage|help         $(_ "Display this short usage.")
  setup              $(_ "Setup your build environment.")
  *-setup            $(_ "Setup a cross environment.")
  test               $(_ "Test environment and cook a package.")
  list-wok           $(_ "List packages in the wok.")
  search             $(_ "Simple packages search function.")
  new                $(_ "Create a new package with a receipt.")
  list               $(_ "Cook a list of packages.")
  clean-wok          $(_ "Clean-up all packages files.")
  clean-src          $(_ "Clean-up all packages sources.")
  uncook             $(_ "Check for uncooked packages")
  pkgdb              $(_ "Create packages DB lists and flavors.")

$(_ "\033[1mOptions:\033[0m")
  --clean|-c         Cook : $(_ "clean the package in the wok.")
  --install|-i       Cook : $(_ "cook and install the package.")
  --getsrc|-gs       Cook : $(_ "get the package source tarball.")
  --block|-b         Cook : $(_ "block a package so cook will skip it.")
  --unblock|-ub      Cook : $(_ "unblock a blocked package.")
  --cdeps            Cook : $(_ "check dependencies of cooked package.")
  --pack             Cook : $(_ "repack an already built package.")
  --debug            Cook : $(_ "display debugging messages.")
  --continue         Cook : $(_ "continue running compile_rules.")
  --interactive|-x   New  : $(_ "create a receipt interactively.")
  --wok              Setup: $(_ "clone the cooking wok from Hg repo.")
  --stable           Setup: $(_ "clone the stable wok from Hg repo.")
  --undigest         Setup: $(_ "clone the undigest wok from Hg repo.")
  --tiny             Setup: $(_ "clone the tiny SliTaz wok from Hg repo.")
  --forced           Setup: $(_ "force reinstall of chroot packages.")
  --flavors          Pkgdb: $(_ "create up-to-date flavors files.")

EOT
	exit 0
}

# We don't want these escapes in web interface.
clean_log() {
	sed -i -e s'|\[70G\[ \[1;32m| |' \
		-e s'|\[0;39m \]||' $LOGS/$pkg.log
}

# Be sure package exists in wok.
check_pkg_in_wok() {
	if [ ! -d "$WOK/$pkg" ]; then
		newline; _ "Unable to find package in the wok: \$pkg"; newline
		exit 1
	fi
}

if_empty_value() {
	if [ -z "$value" ]; then
		# L10n: QA is quality assurance
		_ "QA: empty variable: \${var}=\"\""; newline
		exit 1
	fi
}

# Initialize files used in $CACHE
init_db_files() {
	_ "Creating directories structure in: \$SLITAZ"
	mkdir -p $WOK $PKGS $SRC $CACHE $LOGS $FEEDS
	_ "Creating DB files in: \$CACHE"
	for f in $activity $command $broken $blocked
	do
		touch $f
	done
}

# QA: check a receipt consistency before building.
receipt_quality() {
	_ "QA: checking package receipt..."
	unset online
	if ifconfig | grep -q -A 1 "^[a-z]*[0-9]" | fgrep 'addr:'; then
		online="online"
	fi
	for var in PACKAGE VERSION CATEGORY SHORT_DESC MAINTAINER WEB_SITE
	do
		unset value
		value="$(. $receipt ; eval echo \$$var)"
		case "$var" in
			PACKAGE|VERSION|SHORT_DESC)
				if_empty_value ;;
			CATEGORY)
				[ -z "$value" ] && value="empty"
				valid="$(echo $PKGS_CATEGORIES)" # avoid newlines
				if ! echo "$valid" | grep -q -w "$value"; then
					_ "QA: unknown category: \$value"
					_ "Please, use one of: \$valid" | busybox fold -s
					newline; exit 1
				fi ;;
			WEB_SITE)
				# We don't check WGET_URL since if dl is needed it will fail.
				# Break also if we're not online. Here error is not fatal.
				if_empty_value
				[ -z "$online" ] || break
				if ! busybox wget -T 12 -s $value 2>/dev/null; then
					_ "QA: unable to reach: \$value"
				fi ;;
		esac
	done
}

# Paths used in receipt and by cook itself.
set_paths() {
	pkgdir=$WOK/$PACKAGE
	basesrc=$pkgdir/source
	tmpsrc=$basesrc/tmp
	src=$basesrc/$PACKAGE-$VERSION
	taz=$pkgdir/taz
	pack=$taz/$PACKAGE-${VERSION}${EXTRAVERSION}
	fs=$pack/fs
	stuff=$pkgdir/stuff
	install=$pkgdir/install
	pkgsrc="${SOURCE:-$PACKAGE}-${KBASEVER:-$VERSION}"
	lzma_tarball="$pkgsrc.tar.lzma"
	if [ "$PATCH" ]; then
		[ "${PTARBALL}" ] || PTARBALL="$(basename $PATCH)"
	fi
	if [ "$WANTED" ]; then
		basesrc=$WOK/$WANTED/source
		src=$basesrc/$WANTED-$VERSION
		install=$WOK/$WANTED/install
		wanted_stuff=$WOK/$WANTED/stuff
	fi
	if [ "$SOURCE" ]; then
		source_stuff=$WOK/$SOURCE/stuff
	fi
	# Kernel version is set from wok/linux or installed/linux-api-headers(wok-undigest)
	if [ -f "$WOK/linux/receipt" ]; then
		kvers=$(grep ^VERSION= $WOK/linux/receipt | cut -d '"' -f 2)
		kbasevers=${kvers:0:3}
	elif [ -f "$INSTALLED/linux-api-headers/receipt" ]; then
		kvers=$(grep ^VERSION= $INSTALLED/linux-api-headers/receipt | cut -d '"' -f 2)
		kbasevers=${kvers:0:3}
	fi
	# Python version
	if [ -f "$WOK/python/receipt" ]; then
		pyvers=$(grep ^VERSION= $WOK/python/receipt | cut -d '"' -f 2)
	fi
	# perl version for some packages needed it
	if [ -f "$WOK/perl/receipt" ]; then
		perlvers=$(grep ^VERSION= $WOK/perl/receipt | cut -d '"' -f 2)
	fi
	# Old way compatibility.
	_pkg=$install
}

# Create source tarball when URL is a SCM.
create_tarball() {
	local tarball
	tarball=$pkgsrc.tar.bz2
	[ "$LZMA_SRC" ] && tarball=$lzma_tarball
	_ "Creating tarball: \$tarball"
	if [ "$LZMA_SRC" ]; then
		tar -c $pkgsrc | lzma e $SRC/$tarball -si $LZMA_SET_DIR || exit 1
		LZMA_SRC=""
	else
		tar cjf $tarball $pkgsrc || exit 1
		mv $tarball $SRC && rm -rf $pkgsrc
	fi
	TARBALL=$tarball
}

# Get package source. For SCM we are in cache so clone here and create a
# tarball here.
get_source() {
	local url
	url="$MIRROR_URL/sources/packages/${TARBALL:0:1}/$TARBALL"
	set_paths
	pwd=$(pwd)
	case "$WGET_URL" in
		http://*|ftp://*)
			# Busybox Wget is better!
			busybox wget -T 60 -c -O $SRC/$TARBALL $WGET_URL || \
			busybox wget -T 60 -c -O $SRC/$TARBALL $url || \
				(_ "ERROR: wget \$WGET_URL" && exit 1) ;;
		https://*)
			wget -c --no-check-certificate -O $SRC/$TARBALL $WGET_URL || \
			busybox wget -T 60 -c -O $SRC/$TARBALL $url || \
				(_ "ERROR: wget \$WGET_URL" && exit 1) ;;
		hg*|mercurial*)
			if $(echo "$WGET_URL" | fgrep -q "hg|"); then
				url=${WGET_URL#hg|}
			else
				url=${WGET_URL#mercurial|}
			fi
			_ "Getting source from Hg..."
			_ "URL: \$url"
			_ "Cloning to: \$pwd/\$pkgsrc"
			if [ "$BRANCH" ]; then
				_ "Hg branch: \$BRANCH"
				hg clone $url --rev $BRANCH $pkgsrc || \
					(_ "ERROR: hg clone \$url --rev \$BRANCH" && exit 1)
			else
				hg clone $url $pkgsrc || (_ "ERROR: hg clone \$url" && exit 1)
			fi
			rm -rf $pkgsrc/.hg
			create_tarball ;;
		git*)
			url=${WGET_URL#git|}
			_ "Getting source from Git..."
			_ "URL: \$url"
			cd $SRC
			git clone $url $pkgsrc || (_ "ERROR: git clone \$url" && exit 1)
			if [ "$BRANCH" ]; then
				_ "Git branch: \$BRANCH"
				cd $pkgsrc && git checkout $BRANCH && cd ..
			fi
			cd $SRC
			create_tarball ;;
		cvs*)
			url=${WGET_URL#cvs|}
			mod=$PACKAGE
			[ "$CVS_MODULE" ] && mod=$CVS_MODULE
			_ "Getting source from CVS..."
			_ "URL: \$url"
			[ "$CVS_MODULE" ] && _ "CVS module: \$mod"
			_ "Cloning to: \$pwd/\$mod"
			cvs -d:$url co $mod && mv $mod $pkgsrc
			create_tarball ;;
		svn*|subversion*)
			if $(echo "$WGET_URL" | fgrep -q "svn|"); then
				url=${WGET_URL#svn|}
			else
				url=${WGET_URL#subversion|}
			fi
			_ "Getting source from SVN..."
			_ "URL: \$url"
			if [ "$BRANCH" ]; then
				echo t | svn co $url -r $BRANCH $pkgsrc
			else
				echo t | svn co $url $pkgsrc
			fi
			create_tarball ;;
		bzr*)
			url=${WGET_URL#bzr|}
			_ "Getting source from bazaar..."
			cd $SRC
			pkgsrc=${url#*:}
			if [ "$BRANCH" ]; then
				echo "bzr -Ossl.cert_reqs=none branch $url -r $BRANCH"
				bzr -Ossl.cert_reqs=none branch $url -r $BRANCH
			else
				echo "bzr -Ossl.cert_reqs=none branch $url"
				bzr -Ossl.cert_reqs=none branch $url
				cd $pkgsrc && BRANCH=$(bzr revno) && cd ..
				_ "Don't forget to add to receipt:"
				echo 'BRANCH="'$BRANCH'"'; newline
			fi
			mv $pkgsrc $pkgsrc-$BRANCH
			pkgsrc=$pkgsrc-$BRANCH
			create_tarball ;;
		*)
			(newline; _ "ERROR: Unable to handle: \$WGET_URL"; newline) | \
				tee -a $LOGS/$PACKAGE.log
			exit 1 ;;
	esac
}

# Extract source package.
extract_source() {
	if [ ! -s "$SRC/$TARBALL" ]; then
		local url
		url="$MIRROR_URL/sources/packages"
		url=$url/${TARBALL:0:1}/$TARBALL
		_ "Getting source from mirror: \$url"
		busybox wget -c -P $SRC $url || _ "ERROR: wget \$url"
	fi
	_ "Extracting: \$TARBALL"
	case "$TARBALL" in
		*.tar.gz|*.tgz) tar xzf $SRC/$TARBALL 2>/dev/null ;;
		*.tar.bz2|*.tbz|*.tbz2) tar xjf $SRC/$TARBALL 2>/dev/null ;;
		*.tar.lzma) tar xaf $SRC/$TARBALL ;;
		*.tar.lz|*.tlz) lzip -d < $SRC/$TARBALL | tar xf - 2>/dev/null ;;
		*.tar) tar xf $SRC/$TARBALL ;;
		*.zip|*.xpi) unzip -o $SRC/$TARBALL ;;
		*.xz) unxz -c $SRC/$TARBALL | tar xf - || tar xf $SRC/$TARBALL 2>/dev/null;;
		*.7z) 7zr x $SRC/$TARBALL ;;
		*.Z) uncompress -c $SRC/$TARBALL | tar xf - ;;
		*.rpm) rpm2cpio $SRC/$TARBALL | cpio -idm --quiet ;;
		*.run) /bin/sh $SRC/$TARBALL $RUN_OPTS ;;
		*) cp $SRC/$TARBALL $(pwd) ;;
	esac
}

# Display cooked package summary.
summary() {
	cd $WOK/$pkg
	[ -d $WOK/$pkg/install ] && prod=$(du -sh $WOK/$pkg/install | awk '{print $1}' 2>/dev/null)
	[ -d $WOK/$pkg/source ] && srcdir=$(du -sh $WOK/$pkg/source | awk '{print $1}' 2>/dev/null)
	fs=$(du -sh $WOK/$pkg/taz/* | awk '{print $1}')
	size=$(du -sh $PKGS/$pkg-${VERSION}*.tazpkg | awk '{print $1}')
	files=$(cat $WOK/$pkg/taz/$pkg-*/files.list | wc -l)
	[ "$TARBALL" ] && srcsize=$(du -sh $SRC/$TARBALL | awk '{print $1}')
	cookdate=$(date "$(_ '+%Y-%m-%d %H:%M')")
	sec=$time
	div=$(( ($time + 30) / 60))
	# L10n: 'm' is for minutes (approximate cooking time)
	min=$(_n "~ \${div}m"); [ "$div" = 0 ] && min=""
	_ "Summary for: \$PACKAGE \$VERSION"
	separator
	# L10n: keep the same width of translations to get a consistent view
	[ "$srcdir" ]  && _ "Source dir  : \$srcdir"
	[ "$TARBALL" ] && _ "Src file    : \$TARBALL"
	[ "$srcsize" ] && _ "Src size    : \$srcsize"
	[ "$prod" ]    && _ "Produced    : \$prod"
	_ "Packed      : \$fs"
	_ "Compressed  : \$size"
	_ "Files       : \$files"
	# L10n: 's' is for seconds (cooking time)
	_ "Cook time   : \${sec}s \$min"
	_ "Cook date   : \$cookdate"
	_ "Host arch   : \$ARCH"
	separator
}

# Display debugging error info.
debug_info() {
	newline; _ "Debug information"; separator
	# L10n: specify your format of date and time (to help: man date)
	# L10n: not bad one is '+%x %R'
	datenow=$(date "$(_ '+%Y-%m-%d %H:%M')")
	_ "Cook date: \$datenow"
	# L10n: Please, translate all messages beginning with ERROR in a same way
	lerror=$(_n "ERROR")
	for error in \
		ERROR $lerror "No package" "cp: can't" "can't open" "can't cd" \
		"error:" "fatal error:" "undefined reference to" \
		"Unable to connect to" "link: cannot find the library" \
		"CMake Error" ": No such file or directory"
	do
		fgrep "$error" $LOGS/$pkg.log
	done > $LOGS/$pkg.log.debug_info 2>&1
	cat $LOGS/$pkg.log.debug_info
	rm -f $LOGS/$pkg.log.debug_info
	separator; newline
}

# 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.
copy_generic_files()
{
	# $LOCALE is set in cook.conf
	if [ "$LOCALE" -a "$WANTED" = "" ]; then
		if [ -d "$install/usr/share/locale" ]; then
			mkdir -p $fs/usr/share/locale
			for i in $LOCALE
			do
				if [ -d "$install/usr/share/locale/$i" ]; then
					cp -a $install/usr/share/locale/$i $fs/usr/share/locale
				fi
			done
		fi
	fi

	# Generic pixmaps copy can be disabled with GENERIC_PIXMAPS="no"
	if [ "$GENERIC_PIXMAPS" != "no" ]; then
		if [ -d "$install/usr/share/pixmaps" ]; then
			mkdir -p $fs/usr/share/pixmaps
			if [ -f "$install/usr/share/pixmaps/$PACKAGE.png" ]; then
				cp -a $install/usr/share/pixmaps/$PACKAGE.png \
					$fs/usr/share/pixmaps
			elif [ -f "$install/usr/share/pixmaps/$PACKAGE.xpm" ]; then
				cp -a $install/usr/share/pixmaps/$PACKAGE.xpm \
					$fs/usr/share/pixmaps
			fi
		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).
	# Generic desktop entry copy can be disabled with GENERIC_MENUS="no"
	if [ "$GENERIC_MENUS" != "no" ]; then
		if [ -d "$install/usr/share/applications" ] && [ "$WANTED" == "" ]; then
			mkdir -p $fs/usr/share
			cp -a $install/usr/share/applications $fs/usr/share
		fi
	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

	# Add custom licenses
	if [ -d "$stuff/licenses" ]; then
		mkdir -p $fs/usr/share/licenses
		cp -a $stuff/licenses $fs/usr/share/licenses/$PACKAGE
	fi
}

# Find and strip: --strip-all (-s) or --strip-debug on static libs as well
# as removing unneeded files like in Python packages. Cross compiled binaries
# must be stripped with cross-tools aka $ARCH-slitaz-*-strip
strip_package() {
	case "$ARCH" in
		arm*|x86_64) export STRIP=${HOST_SYSTEM}-strip ;;
		*) export STRIP=strip ;;
	esac
	_n "Executing strip on all files..."
	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
	find $fs -name "*.so*" -exec $STRIP -s '{}' 2>/dev/null \;
	find $fs -name "*.a" -exec $STRIP --strip-debug '{}' 2>/dev/null \;
	status

	# Remove Python .pyc and .pyo from packages.
	if echo "$PACKAGE $DEPENDS" | fgrep -q "python"; then
		_n "Removing Python compiled files..."
		find $fs -type f -name "*.pyc" -delete 2>/dev/null
		find $fs -type f -name "*.pyo" -delete 2>/dev/null
		status
	fi

	# Remove Perl perllocal.pod and .packlist from packages.
	if echo "$DEPENDS" | fgrep -q "perl"; then
		_n "Removing Perl compiled files..."
		find $fs -type f -name "perllocal.pod" -delete 2>/dev/null
		find $fs -type f -name ".packlist" -delete 2>/dev/null
		status
	fi
}

# Remove installed deps.
remove_deps() {
	# Now remove installed build deps.
	diff="/tmp/installed.cook.diff"
	if [ -s $diff ]; then
		deps=$(cat $diff | grep ^+[a-zA-Z0-9] | sed s/^+//)
		nb=$(cat $diff | grep ^+[a-zA-Z0-9] | wc -l)
		_n "Build dependencies to remove: "; echo $nb $root
		_n "Removing:"
		for dep in $deps
		do
			echo -n " $dep"
			echo 'y' | tazpkg remove $dep --root=$root >/dev/null
		done
		newline; newline
		# Keep the last diff for debug and info.
		mv -f $diff $CACHE/installed.diff
	fi
}

# The main cook function.
cookit() {
	_ "Cook: \$PACKAGE \$VERSION"; separator
	set_paths

	# Handle cross-tools.
	case "$ARCH" in
		arm*|x86_64)
			# CROSS_COMPILE is used by at least Busybox and the kernel to set
			# the cross-tools prefix. Sysroot is the root of our target arch
			sysroot=$CROSS_TREE/sysroot
			tools=$CROSS_TREE/tools
			# Set root path when cross compiling. ARM tested but not x86_64
			# When cross compiling we must install build deps in $sysroot.
			arch="-${ARCH}"
			root=$sysroot
			_ "\$ARCH sysroot: \$sysroot"
			_ "Adding \$tools/bin to PATH"
			export PATH=$PATH:$tools/bin
			export PKG_CONFIG_PATH=$sysroot/usr/lib/pkgconfig
			export CROSS_COMPILE=${HOST_SYSTEM}-
			_ "Using cross-tools: \$CROSS_COMPILE"
			if [ "$ARCH" == "x86_64" ]; then
				export CC="${HOST_SYSTEM}-gcc -m64"
				export CXX="${HOST_SYSTEM}-g++ -m64"
			else
				export CC=${HOST_SYSTEM}-gcc
				export CXX=${HOST_SYSTEM}-g++
			fi
			export AR=${HOST_SYSTEM}-ar
			export AS=${HOST_SYSTEM}-as
			export RANLIB=${HOST_SYSTEM}-ranlib
			export LD=${HOST_SYSTEM}-ld
			export STRIP=${HOST_SYSTEM}-strip
			export LIBTOOL=${HOST_SYSTEM}-libtool ;;
	esac

	[ "$QA" ] && receipt_quality
	cd $pkgdir
	[ "$continue" ] || rm -rf source 2> /dev/null
	rm -rf install taz 2> /dev/null

	# Disable -pipe if less than 512Mb free RAM.
	free=$(free | fgrep '/+ buffers' | tr -s ' ' | cut -f 4 -d ' ')
	if [ "$free" -lt 524288 ] && [ "$CFLAGS" != "${CFLAGS/-pipe}" ]; then
		_ "Disabling -pipe compile flag: \$free RAM"
		CFLAGS="${CFLAGS/-pipe}" && CFLAGS=$(echo "$CFLAGS" | tr -s ' ')
		CXXFLAGS="${CXXFLAGS/-pipe}" && CXXFLAGS=$(echo "$CXXFLAGS" | tr -s ' ')
	fi
	unset free

	# Export flags and path to be used by make and receipt.
	DESTDIR=$pkgdir/install
	# FIXME: L10n: Is this the right time for 'LC_ALL=C LANG=C'?
	export DESTDIR MAKEFLAGS CFLAGS CXXFLAGS CONFIG_SITE LC_ALL=C LANG=C
	#LDFLAGS

	# Check for build deps and handle implicit depends of *-dev packages
	# (ex: libusb-dev :: libusb).
	rm -f $CACHE/installed.local $CACHE/installed.web $CACHE/missing.dep
	touch $CACHE/installed.local $CACHE/installed.web
	[ "$BUILD_DEPENDS" ] && _ "Checking build dependencies..."
	[ "$root" ] && _ "Using packages DB: \${root}\$DB"
	for dep in $BUILD_DEPENDS
	do
		implicit=${dep%-dev}
		for i in $dep $implicit
		do
			if [ ! -f "${root}$INSTALLED/$i/receipt" ]; then
				# Try local package first. In some cases implicit doesn't exist, ex:
				# libboost-dev exists but not libboost, so check if we got vers.
				unset vers
				vers=$(. $WOK/$i/receipt 2>/dev/null ; echo $VERSION)
				# We may have a local package.
				if [ ! "$vers" ]; then
					vers=$(grep "^$i |" $PKGS/packages.desc | awk '{print $3}')
				fi
				debug "bdep: $i version: $vers"
				if [ -f "$PKGS/$i-${vers}${arch}.tazpkg" ]; then
					echo $i-${vers}${arch}.tazpkg >> $CACHE/installed.local
				else
					# Priority to package version in wok (maybe more up-to-date)
					# than the mirrored one.
					if [ "$vers" ]; then
						if fgrep -q $i-${vers}${arch} ${root}$DB/packages.list; then
							echo $i >> $CACHE/installed.web
						else
							# So package exists in wok but not available.
							_ "Missing dep (wok/pkg): \$i \$vers"
							echo $i >> $CACHE/missing.dep
						fi
					else
						# Package is not in wok but may be in online repo.
						if fgrep -q $i-${vers}${arch} ${root}$DB/packages.list; then
							echo $i >> $CACHE/installed.web
						else
							_ "ERROR: unknown dep \$i"; exit 1
						fi
					fi
				fi
			fi
		done
	done

	# Get the list of installed packages
	cd ${root}$INSTALLED && ls -1 > $CACHE/installed.list

	# Have we a missing build dep to cook?
	if [ -s "$CACHE/missing.dep" ] && [ "$AUTO_COOK" ]; then
		_ "Auto cook config is set: AUTO_COOK"
		cp -f $LOGS/$PACKAGE.log $LOGS/$PACKAGE.log.$$
		for i in $(uniq $CACHE/missing.dep)
		do
			(_ "Building dep (wok/pkg)    : \$i \$vers") | \
				tee -a $LOGS/$PACKAGE.log.$$
			# programmers: next two messages are exact copy from remove_deps()
			togrep1=$(_n "Build dependencies to remove: ")
			togrep2=$(_n "Removing:")
			cook $i || (_ "ERROR: can't cook dep '\$i'" && newline && \
				fgrep $togrep1 $LOGS/$i.log && \
				fgrep $togrep2 $LOGS/$i.log && newline) | \
				tee -a $LOGS/$PACKAGE.log.$$ && break
		done
		rm -f $CACHE/missing.dep
		mv  $LOGS/$PACKAGE.log.$$ $LOGS/$PACKAGE.log
	fi

	# QA: Exit on missing dep errors. We exit in both cases, if AUTO_COOK
	# is enabled and cook fails we have ERROR in log, if no auto cook we have
	# missing dep in cached file.
	lerror=$(_n "ERROR")
	if fgrep -q ^$lerror $LOGS/$pkg.log || [ -s "$CACHE/missing.dep" ]; then
		[ -s "$CACHE/missing.dep" ] && nb=$(cat $CACHE/missing.dep | wc -l)
		_ "ERROR: missing dep \$nb" && exit 1
	fi

	# Install local packages: package-version${arch}
	cd $PKGS
	for i in $(uniq $CACHE/installed.local)
	do
		_ "Installing dep (pkg/local): \$i"
		tazpkg install $i --root=$root >/dev/null
	done

	# Install web or cached packages (if mirror is set to $PKGS we only
	# use local packages).
	for i in $(uniq $CACHE/installed.web)
	do
		_ "Installing dep (web/cache): \$i"
		tazpkg get-install $i --root=$root >/dev/null
	done

	# If a cook failed deps are removed.
	cd ${root}$INSTALLED && ls -1 > $CACHE/installed.cook && cd $CACHE
	[ ! -s "/tmp/installed.cook.diff" ] && \
		busybox diff installed.list installed.cook > /tmp/installed.cook.diff
	deps=$(cat /tmp/installed.cook.diff | grep ^+[a-zA-Z0-9] | wc -l)

	# Get source tarball and make sure we have source dir named:
	# $PACKAGE-$VERSION to be standard in receipts. Here we use tar.lzma
	# tarball if it exists.
	if [ "$WGET_URL" ] && [ ! -f "$SRC/$TARBALL" ]; then
		if [ -f "$SRC/${SOURCE:-$PACKAGE}-$VERSION.tar.lzma" ]; then
			TARBALL=${SOURCE:-$PACKAGE}-$VERSION.tar.lzma
			LZMA_SRC=""
		else
			get_source || exit 1
		fi
	fi
	if [ ! "$WANTED" ] && [ "$TARBALL" ] && [ ! -d "$src" ]; then
		mkdir -p $pkgdir/source/tmp && cd $pkgdir/source/tmp
		if ! extract_source ; then
			get_source
			extract_source || exit 1
		fi
		if [ "$LZMA_SRC" ]; then
			cd $pkgdir/source
			if [ "$(ls -A tmp | wc -l)" -gl 1 ] || [ -f "$(echo tmp/*)" ]; then
				mv tmp tmp-1 && mkdir tmp
				mv tmp-1 tmp/${SOURCE:-$PACKAGE}-$VERSION
			fi
			if [ -d "tmp/${SOURCE:-$PACKAGE}-$VERSION" ]; then
				cd tmp && tar -c * | lzma e $SRC/$TARBALL -si
			fi
		fi
		cd $pkgdir/source/tmp
		# Some archives are not well done and don't extract to one dir (ex lzma).
		files=$(ls | wc -l)
		[ "$files" == 1 ] && [ -d "$(ls)" ] && mv * ../$PACKAGE-$VERSION
		[ "$files" == 1 ] && [ -f "$(ls)" ] && mkdir -p ../$PACKAGE-$VERSION && \
			mv * ../$PACKAGE-$VERSION/$TARBALL
		[ "$files" -gt 1 ]  && mkdir -p ../$PACKAGE-$VERSION && \
			mv * ../$PACKAGE-$VERSION
		cd .. && rm -rf tmp
	fi

	# Libtool shared libs path hack.
	case "$ARCH" in
		arm*) cross libhack ;;
	esac

	# Execute receipt rules.
	if grep -q ^compile_rules $receipt; then
		_ "Executing: compile_rules"
		echo "CFLAGS   : $CFLAGS"
		#echo "LDFLAGS  : $LDFLAGS"
		[ -d "$src" ] && cd $src
		compile_rules $@ || exit 1
		# Stay compatible with _pkg
		[ -d "$src/_pkg" ] && mv $src/_pkg $install
		# QA: compile_rules success so valid.
		mkdir -p $install
	else
		# QA: no compile_rules so no error, valid.
		mkdir -p $install
	fi
	separator; newline

	# Execute testsuite.
	if grep -q ^testsuite $receipt; then
		_ "Running testsuite"; separator
		testsuite $@ || exit 1
		separator; newline
	fi
}

# Cook quality assurance.
cookit_quality() {
	if [ ! -d "$WOK/$pkg/install" ] && [ ! "$WANTED" ]; then
		_ "ERROR: cook failed" | tee -a $LOGS/$pkg.log
	fi
	# ERROR can be echoed any time in cookit()
	lerror=$(_n "ERROR")
	if grep -Ev "(conftest|configtest)" $LOGS/$pkg.log | \
	   grep -Eq "(^$lerror|undefined reference to)" ; then
		debug_info | tee -a $LOGS/$pkg.log
		rm -f $command && exit 1
	fi
}

# Create the package. Wanted to use Tazpkg to create a tazpkg package at first,
# but it doesn't handle EXTRAVERSION.
packit() {
	set_paths

	# Handle cross compilation
	case "$ARCH" in
		arm*|x86_64) arch="-$ARCH" ;;
	esac

	_ "Pack: \$PACKAGE \${VERSION}\${arch}"; separator

	if grep -q ^genpkg_rules $receipt; then
		_ "Executing: genpkg_rules"
		set -e && cd $pkgdir && mkdir -p $fs
		genpkg_rules || (newline; _ "ERROR: genpkg_rules failed"; newline) >> \
			$LOGS/$pkg.log
	else
		_ "No packages rules: meta package"
		mkdir -p $fs
	fi

	# First QA check to stop now if genpkg_rules failed.
	lerror=$(_n "ERROR")
	if fgrep -q ^$lerror $LOGS/$pkg.log; then
		exit 1
	fi

	cd $taz
	for file in receipt description.txt
	do
		[ ! -f "../$file" ] && continue
		_n "Copying \$file..."
		cp -f ../$file $pack && chown 0.0 $pack/$file && status
	done
	copy_generic_files

	# Create files.list with redirecting find output.
	_n "Creating the list of files..."
	cd $fs
	find . -type f -print > ../files.list
	find . -type l -print >> ../files.list
	cd .. && sed -i s/'^.'/''/ files.list
	status

	# Strip and stuff files.
	strip_package

	# Md5sum of files.
	_n "Creating md5sum of files..."
	while read file; do
		[ -L "fs$file" ] && continue
		[ -f "fs$file" ] || continue
		case "$file" in
			/lib/modules/*/modules.*|*.pyc) continue ;;
		esac
		md5sum "fs$file" | sed 's/  fs/  /'
	done < files.list > 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.
	_n "Compressing the fs..."
	find fs | cpio -o -H newc --quiet | lzma e fs.cpio.lzma -si
	rm -rf fs
	status
	PACKED_SIZE=$(du -chs fs.cpio.lzma receipt files.list \
		md5sum description.txt 2> /dev/null | awk \
		'{ sz=$1 } END { print sz }')
	_n "Updating 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
	status

	# Set extra version.
	if [ "$EXTRAVERSION" ]; then
		_n "Updating receipt EXTRAVERSION: \$EXTRAVERSION"
		sed -i s/^EXTRAVERSION.*$// receipt
		sed -i "s/^VERSION=/EXTRAVERSION=\"$EXTRAVERSION\"\nVERSION=/" receipt
		status
	fi

	# Compress.
	_n "Creating full cpio archive..."
	find . -print | cpio -o -H newc --quiet > \
		../$PACKAGE-${VERSION}${EXTRAVERSION}${arch}.tazpkg
	status
	_n "Restoring original package tree..."
	unlzma -c fs.cpio.lzma | cpio -idm --quiet
	status
	rm fs.cpio.lzma && cd ..

	# QA and give info.
	tazpkg=$(ls *.tazpkg)
	packit_quality
	separator; _ "Package: \$tazpkg"; newline
}

# Verify package quality and consistency.
packit_quality() {
	#gettext "QA: checking for broken link..."
	#link=$(find $fs/usr -type l -follow)
	#[ "$link" ] && echo -e "\nERROR: broken link in filesystem"
	#status

	# Exit if any error found in log file.
	lerror=$(_n "ERROR")
	if fgrep -q ^$lerror $LOGS/$pkg.log; then
		rm -f $command && exit 1
	fi

	_n "QA: checking for empty package..."
	files=$(cat $WOK/$pkg/taz/$pkg-*/files.list | wc -l)
	if [ "$files" == 0 ] && [ "$CATEGORY" != "meta" ]; then
		newline; _ "ERROR: empty package"
		rm -f $command && exit 1
	else
		# Ls sort by name so the first file is the one we want.
		old=$(ls $PKGS/$pkg-*.tazpkg 2>/dev/null | head -n 1)
		status
		if [ -f "$old" ]; then
			old_pkg=$(basename $old)
			_n "Removing old: \$old_pkg"
			rm -f $old && status
		fi
		mv -f $pkgdir/taz/$pkg-*.tazpkg $PKGS
		sed -i /^${pkg}$/d $broken
		#gettext "Removing source tree..."
		#rm -f $WOK/$pkg/source && status
	fi
}

# Tic tac, tic tac...
tac() {
	sed '1!G;h;$!d' $1
}

# Install package on --install or update the chroot.
install_package() {
	case "$ARCH" in
		arm*|x86_64)
			arch="-${ARCH}"
			root=$CROSS_TREE/sysroot ;;
	esac
	# Install package if requested but skip install if target host doesn't
	# match build system or it will break the build chroot.
	build=$(echo $BUILD_SYSTEM | cut -d "-" -f 1)
	if [ "$inst" ] && [ "$build" == "$ARCH" ]; then
		if [ -f "$PKGS/$PACKAGE-${VERSION}${EXTRAVERSION}.tazpkg" ]; then
			cd $PKGS && tazpkg install \
				$PACKAGE-${VERSION}${EXTRAVERSION}.tazpkg --forced
		else
			_ "Unable to install package, build has failed."; newline
			exit 1
		fi
	fi

	# Install package if part of the chroot to keep env up-to-date.
	if [ -d "${root}$INSTALLED/$pkg" ]; then
		. /etc/slitaz/cook.conf
		. $WOK/$pkg/taz/$pkg-*/receipt
		_ "Updating \$ARCH chroot environment..."
		_ "Updating chroot: \$pkg (\${VERSION}\${EXTRAVERSION}\${arch})" | log
		cd $PKGS && tazpkg install \
			$pkg-${VERSION}${EXTRAVERSION}${arch}.tazpkg \
			--forced --root=$root
	fi
}

# remove chroot jail
umount_aufs() {
	tac ${1}rw/aufs-umount.sh | sh
	rm -rf ${1}rw
	umount ${1}root
	rmdir ${1}r*
}

# Launch the cook command into a chroot jail protected by aufs.
# The current filesystems are used read-only and updates are
# stored in a separate branch.
try_aufs_chroot() {

	base=/dev/shm/aufsmnt$$

	# Can we setup the chroot? Is it already done?
	grep -q ^AUFS_NOT_SUPPORTED $receipt && return
	grep -q ^AUFS_NOT_RAMFS $receipt && base=/mnt/aufsmnt$$
	[ -n "$AUFS_MOUNTS" -a ! -f /aufs-umount.sh ] || return
	lsmod | grep -q aufs || modprobe aufs 2> /dev/null || return
	mkdir ${base}root ${base}rw || return

	_ "Setup aufs chroot..."

	# Sanity check
	for i in / /proc /sys /dev/shm /home ; do
		case " $AUFS_MOUNTS " in
		*\ $i\ *) ;;
		*)	AUFS_MOUNTS="$AUFS_MOUNTS $i" ;;
		esac
	done
	for mnt in $(ls -d $AUFS_MOUNTS | sort | uniq); do
		mount --bind $mnt ${base}root$mnt
		if [ $mnt == / ] && ! mount -t aufs -o br=${base}rw:/ none ${base}root; then
			_ "Aufs mountage failure"
			umount ${base}root
			rm -rf ${base}r*
			return
		fi
		echo "umount ${base}root$mnt" >> ${base}rw/aufs-umount.sh
	done
	trap "umount_aufs ${base}" INT

	chroot ${base}root $(cd $(dirname $0); pwd)/$(basename $0) "$@"
	status=$?

	_ "Leaving aufs chroot..."
	umount_aufs ${base}
	# Install package outside the aufs jail
	install_package
	exit $status
}

# Create a XML feed for freshly built packages.
gen_rss() {
	pubdate=$(date "+%a, %d %b %Y %X")
	cat > $FEEDS/$pkg.xml << EOT
	<item>
		<title>$PACKAGE $VERSION${EXTRAVERSION}</title>
		<link>${COOKER_URL}?pkg=$PACKAGE</link>
		<guid>$PACKAGE-$VERSION${EXTRAVERSION}</guid>
		<pubDate>$pubdate</pubDate>
		<description>$SHORT_DESC</description>
	</item>
EOT
}

# Truncate stdout log file to $1 Mb.
loglimit()
{
	if [ -n "$DEFAULT_LOG_LIMIT" ]; then
		tee /dev/stderr | head -qc ${1:-$DEFAULT_LOG_LIMIT}m
	else
		tee /dev/stderr
	fi
}

# Search file in mirrored packages
search_file_mirror()
{
	busybox unlzma -c $DB/files.list.lzma | grep $1\$ | cut -d: -f1 | sort -u
}

# Search file in local wok packages
search_file_local()
{
	# existing packages have precedence over the package/taz folder
	srch=$1
	{ for package in $(find $PKGS -name '*.tazpkg'); do
		if [ ! "x$(busybox cpio --to-stdout --quiet -i files.list < $package | grep /$srch\$)" == "x" ]; then
			busybox cpio -i receipt < $package | fgrep PACKAGE | cut -d\" -f2
		fi
	done } | sort -u
}

# Ask in multiple choice
ask_multiple()
{
	local multiples first my_choice
	multiples="$1"
	first=$(echo "$multiples" | head -n1)
	newline; _ "Multiple choice:\n$multiples\n"
	_ "Select one [$first]: "; read my_choice
	[ "x$my_choice" == "x" ] && my_choice="$first"
	found=$my_choice
}

# Search file in local cache (fast), local wok packages, mirrored packages
search_file()
{
	local srch cache missing
	srch=$1
	cache=/var/cache/ldsearch.cache
	missing=/var/cache/missing.file
	touch $cache $missing
	found=$(grep $srch $cache | cut -d'	' -f2)
	if [ "x$found" == "x" ]; then
		found=$(search_file_local $srch)
		if [ "x$found" != "x" ]; then
			if [ $(echo "$found" | wc -l) -gt 1 ]; then
				ask_multiple "$found"
			fi
			echo "$srch	$found" >> $cache
		else
			found=$(search_file_mirror $srch)
			if [ "x$found" != "x" ]; then
				if [ $(echo "$found" | wc -l) -gt 1 ]; then
					ask_multiple "$found"
				fi
				echo "$srch	$found" >> $cache
			else
				echo "$srch" >> $missing
			fi
		fi
	fi
}

#
# Receipt functions to ease packaging
#

get_dev_files() {
	_n "Getting standard devel files..."
	mkdir -p $fs/usr/lib
	cp -a $install/usr/lib/*.so* $fs/usr/lib
	cp -a $install/usr/lib/pkgconfig $fs/usr/lib
	cp -a $install/usr/include $fs/usr
	status
}

#
# Commands
#

case "$1" in
	usage|help|-u|-h)
		 usage ;;
	list-wok)
		newline; _ "List of \$ARCH packages in: \$WOK"; separator
		cd $WOK
		if [ "$ARCH" != "i486" ]; then
			count=0
			for pkg in $(fgrep 'HOST_ARCH=' */receipt | egrep "$ARCH|any" | cut -d : -f 1)
			do
				unset HOST_ARCH
				. $pkg
				count=$(($count + 1))
				colorize 34 "$PACKAGE"
			done
		else
			count=$(ls | wc -l)
			ls -1
		fi
		separator
		_n "Packages:"; colorize 32 " $count"
		newline ;;
	activity)
		cat $activity ;;
	search)
		# Just a simple search function, we dont need more actually.
		query="$2"
		newline; _ "Search results for: \$query"; separator
		cd $WOK && ls -1 | grep "$query"
		separator; newline ;;
	setup)
		# Setup a build environment
		check_root
		_ "Cook: setup environment" | log
		newline; _ "Setting up your environment"; separator
		cd $SLITAZ
		init_db_files
		_ "Checking for packages to install..."
		# Use setup pkgs from cross.conf or cook.conf. When cross compiling
		# ARCH-setup or 'cross check' should be used before: cook setup
		case "$ARCH" in
			arm*|x86_64)
				if [ ! -x "/usr/bin/cross" ]; then
					_ "ERROR: cross is not installed"
					exit 1
				fi
				_ "Using config file: /etc/slitaz/cross.conf"
				. /etc/slitaz/cross.conf ;;
		esac
		for pkg in $SETUP_PKGS; do
			if [ "$forced" ]; then
				tazpkg -gi $pkg --forced
			else
				[ -d "$INSTALLED/$pkg" ] || tazpkg get-install $pkg
			fi
		done

		# Handle --options
		case "$2" in
			--wok)
				hg clone $WOK_URL wok || exit 1 ;;
			--stable)
				hg clone $WOK_URL-stable wok || exit 1 ;;
			--undigest)
				hg clone $WOK_URL-undigest wok || exit 1 ;;
			--tiny)
				hg clone $WOK_URL-tiny wok || exit 1 ;;
		esac

		# SliTaz group and permissions
		if ! grep -q ^slitaz /etc/group; then
			_ "Adding group: slitaz"
			addgroup slitaz
		fi
		_ "Setting permissions for slitaz group..."
		find $SLITAZ -maxdepth 2 -exec chown root.slitaz {} \;
		find $SLITAZ -maxdepth 2 -exec chmod g+w {} \;
		separator; _ "All done, ready to cook packages :-)"; newline ;;
	*-setup)
		# Setup for cross compiling.
		arch=${1%-setup}
		check_root
		. /etc/slitaz/cook.conf
		for pkg in $CROSS_SETUP; do
			if [ "$forced" ]; then
				tazpkg -gi $pkg --forced
			else
				[ -d "$INSTALLED/$pkg" ] || tazpkg -gi $pkg
			fi
		done
		_ "Cook: setup \$arch cross environment" | log
		newline; boldify $(_n "Setting up your \$arch cross environment"); separator
		init_db_files
		sed -i \
			-e s"/ARCH=.*/ARCH=\"$arch\"/" \
			-e s"/CROSS_TREE=.*/CROSS_TREE=\"\/cross\/$arch\"/" \
			-e s'/BUILD_SYSTEM=.*/BUILD_SYSTEM=i486-slitaz-linux/' \
			/etc/slitaz/cook.conf
		case "$arch" in
			arm)
				flags="-O2 -march=armv6"
				host="$ARCH-slitaz-linux-gnueabi" ;;
			armv6hf)
				flags="-O2 -march=armv6j -mfpu=vfp -mfloat-abi=hard"
				host="$ARCH-slitaz-linux-gnueabi" ;;
			armv7)
				flags="-Os -march=armv7-a -mfpu=vfpv3-d16 -mfloat-abi=softfp -pipe"
				host="$ARCH-slitaz-linux-gnueabi" ;;
			x86_64)
				flags="-O2 -mtune=generic -pipe"
				host="$ARCH-slitaz-linux" ;;
		esac
		sed -i \
			-e s"/CFLAGS=.*/CFLAGS=\"$flags\"/" \
			-e s"/HOST_SYSTEM=.*/HOST_SYSTEM=$host/" /etc/slitaz/cook.conf
		. /etc/slitaz/cook.conf
		sysroot=$CROSS_TREE/sysroot
		tools=/cross/$arch/tools
		root=$sysroot
		# L10n: keep the same width of translations to get a consistent view
		_ "Target arch     : \$ARCH"
		_ "Configure args  : \$CONFIGURE_ARGS"
		_ "Build flags     : \$flags"
		_ "Arch sysroot    : \$sysroot"
		_ "Tools prefix    : \$tools/bin"
		# Tell the packages manager where to find packages.
		_ "Packages DB     : \${root}\$DB"
		mkdir -p ${root}$INSTALLED
		cd ${root}$DB && rm -f *.bak
		for list in packages.list packages.desc packages.equiv packages.md5
		do
			rm -f $list && ln -s $SLITAZ/packages/$list $list
		done
		# We must have the cross compiled glibc-base installed or default
		# i486 package will be used as dep by tazpkg and then break the
		# cross environment
		if [ ! -f "${root}$INSTALLED/glibc-base/receipt" ]; then
			colorize 36 $(_ "WARNING: (e)glibc-base is not installed in sysroot")
		fi
		# Show GCC version or warn if not yet compiled.
		if [ -x "$tools/bin/${HOST_SYSTEM}-gcc" ]; then
			_ "Cross compiler  : \${HOST_SYSTEM}-gcc"
		else
			colorize 36 $(_ "C compiler is missing: \${HOST_SYSTEM}-gcc")
			_ "Run 'cross compile' to cook a toolchain"
		fi
		separator; newline ;;
	test)
		# Test a cook environment.
		_ "Cook test: testing the cook environment" | log
		[ ! -d "$WOK" ] && exit 1
		[ ! -d "$WOK/cooktest" ] && cp -r $DATA/cooktest $WOK
		cook cooktest ;;
	new)
		# Create the package folder and an empty receipt.
		pkg="$2"
		[ "$pkg" ] || usage
		newline
		if [ -d "$WOK/$pkg" ]; then
			_ "\$pkg package already exists."
			exit 1
		fi
		_n "Creating \$WOK/\$pkg"
		mkdir $WOK/$pkg && cd $WOK/$pkg && status
		_n "Preparing the package receipt..."
		cp $DATA/receipt .
		sed -i s"/^PACKAGE=.*/PACKAGE=\"$pkg\"/" receipt
		status && newline

		# Interactive mode, asking and seding.
		case "$3" in
			--interactive|-x)
				_ "Entering interactive mode..."
				separator
				_ "Package       : \$pkg"
				_n "Version       : " ; read answer
				sed -i s/'VERSION=\"\"'/"VERSION=\"$answer\""/ receipt
				_n "Category      : " ; read answer
				sed -i s/'CATEGORY=\"\"'/"CATEGORY=\"$answer\""/ receipt
				# L10n: Short description
				_n "Short desc    : " ; read answer
				sed -i s/'SHORT_DESC=\"\"'/"SHORT_DESC=\"$answer\""/ receipt
				_n "Maintainer    : " ; read answer
				sed -i s/'MAINTAINER=\"\"'/"MAINTAINER=\"$answer\""/ receipt
				_n "License       : " ; read answer
				sed -i s/'LICENSE=\"\"'/"LICENSE=\"$answer\""/ receipt
				_n "Web site      : " ; read answer
				sed -i s#'WEB_SITE=\"\"'#"WEB_SITE=\"$answer\""# receipt
				newline
				# Wget URL.
				_ "Wget URL to download source tarball."
				_n "Example  : " ; echo '$GNU_MIRROR/$PACKAGE/$TARBALL'
				_n "Wget url : " ; read answer
				sed -i s#'WGET_URL=\"$TARBALL\"'#"WGET_URL=\"$answer\""# receipt
				# Ask for a stuff dir.
				_n "Do you need a stuff directory? (y/N) : " ; read answer
				if [ "$answer" = "y" ]; then
					_n "Creating the stuff directory..."
					mkdir $WOK/$pkg/stuff && status
				fi
				# Ask for a description file.
				_n "Are you going to write a description? (y/N) : " ; read answer
				if [ "$answer" = "y" ]; then
					_n "Creating the description.txt file..."
					newline > $WOK/$pkg/description.txt && status
				fi
				separator; _ "Receipt is ready to use."; newline ;;
		esac ;;
	list)
		# Cook a list of packages (better use the Cooker since it will order
		# packages before executing cook).
		check_root
		[ -z "$2" ] && (newline; _ "No list in argument."; newline) && exit 1
		list2=$2
		[ ! -f "$2" ] && (newline; _ "No list found: \$list2"; newline) && exit 1
		_ "Cook list starting: \$list2" | log
		for pkg in $(cat $2)
		do
			cook $pkg || broken
		done ;;
	clean-wok)
		check_root
		newline; _n "Cleaning all packages files..."
		rm -rf $WOK/*/taz $WOK/*/install $WOK/*/source
		status; newline ;;
	clean-src)
		check_root
		newline; _n "Cleaning all packages sources..."
		rm -rf $WOK/*/source
		status; newline ;;
	uncook)
		cd $WOK
		count=0
		newline
		_ "Checking for uncooked packages"
		separator
		for pkg in *
		do
			unset HOST_ARCH EXTRAVERSION
			. $pkg/receipt
			# Source cooked pkg receipt to get EXTRAVERSION
			if [ -d "$WOK/$pkg/taz" ]; then
				cd $WOK/$pkg/taz/$pkg-*
				. receipt && cd $WOK
			fi 
			case "$ARCH" in
				i486)
					debug "Package: $PKGS/${PACKAGE}-${VERSION}${EXTRAVERSION}.tazpkg"
					if [ ! -f "$PKGS/${PACKAGE}-${VERSION}${EXTRAVERSION}.tazpkg" ]; then
						count=$(($count + 1))
						colorize 34 "$pkg"
					fi ;;
				arm*)
					# Check only packages included in arch
					if echo "$HOST_ARCH" | egrep -q "$ARCH|any"; then
						# *.tazpkg
						if [ ! -f "$PKGS/${PACKAGE}-${VERSION}${EXTRAVERSION}-${ARCH}.tazpkg" ]; then
							count=$(($count + 1))
							colorize 34 "$pkg"
						fi
					fi ;;
			esac
		done
		if [ "$count" -gt "0" ]; then
			separator
			_n "Uncooked packages: "; colorize 31 "$count"
		else
			_ "All packages are cooked :-)"
		fi
		newline ;;
	pkgdb)
		# Create suitable packages list for TazPKG and only for built packages
		# as well as flavors files for TazLiTo. We dont need logs since we do it
		# manually to ensure everything is fine before syncing the mirror.
		case "$2" in
			--flavors)
				continue ;;
			*)
				[ "$2" ] && PKGS="$2"
				[ ! -d "$PKGS" ] && \
					newline && _ "Packages directory doesn't exist" && \
					newline && exit 1 ;;
		esac
		time=$(date +%s)
		flavors=$SLITAZ/flavors
		live=$SLITAZ/live
		echo "cook:pkgdb" > $command
		_ "Cook pkgdb: Creating all packages lists" | log
		newline; _ "Creating lists for: \$PKGS"; separator
		datenow=$(date "$(_ '+%Y-%m-%d %H:%M')")
		_ "Cook pkgdb started: \$datenow"
		cd $PKGS
		rm -f packages.* extra.list
		ln -s ../get.list extra.list
		_ "Creating: packages.list"
		ls -1 *.tazpkg | sed s'/.tazpkg//' > $PKGS/packages.list
		_ "Creating: packages.md5"
		md5sum *.tazpkg > $PKGS/packages.md5
		md5sum packages.md5 | cut -f1 -d' ' > ID
		_ "Creating lists from: \$WOK"
		cd $WOK
		for pkg in *
		do
			unset_receipt
			. $pkg/receipt
			# PACKED_SIZE and UNPACKED_SIZE are only in built receipt
			if [ -s $pkg/taz/*/receipt ]; then
				. $pkg/taz/*/receipt
			fi
			if [ -f "$PKGS/$PACKAGE-${VERSION}${EXTRAVERSION}.tazpkg" ] || \
			   [ -f "$PKGS/$PACKAGE-${VERSION}${EXTRAVERSION}-${ARCH}.tazpkg" ]; then

				# packages.desc lets us search easily in DB
				cat >> $PKGS/packages.desc << EOT
$PACKAGE | ${VERSION}$EXTRAVERSION | $SHORT_DESC | $CATEGORY | $WEB_SITE
EOT

				# packages.txt used by tazpkg and tazpkg-web also to provide
				# a human readable package list with version and description.
				cat >> $PKGS/packages.txt << EOT
$PACKAGE
${VERSION}$EXTRAVERSION
$SHORT_DESC
$PACKED_SIZE ($UNPACKED_SIZE installed)

EOT

				# packages.info combines two previous files
				# and will substitute them both
				SIZES=$(echo $PACKED_SIZE $UNPACKED_SIZE | sed 's|\.0||g')
				DEPENDS=$(echo $DEPENDS) # remove newlines from some receipts
				cat >> $PKGS/packages.info << EOT
$PACKAGE	${VERSION}$EXTRAVERSION	$CATEGORY	$SHORT_DESC	$WEB_SITE	$TAGS	$SIZES	$DEPENDS
EOT

				# 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%:*}= $PKGS/packages.equiv; then
						sed -i "s/^${i%:*}=/${i%:*}=$DEST$PACKAGE /" \
							$PKGS/packages.equiv
					else
						echo "${i%:*}=$DEST$PACKAGE" >> $PKGS/packages.equiv
					fi
				done

				# files.list provides a list of all packages files.
				cat $pkg/taz/*/files.list | sed s/^/"$pkg: \0"/ >> \
					$PKGS/files.list
			fi
		done

		# Display list size.
		_ "Done: packages.desc"
		_ "Done: packages.txt"
		_ "Done: packages.equiv"

		# files.list.lzma
		_ "Creating: files.list.lzma"
		touch $PKGS/files.list
		cd $PKGS; lzma e files.list files.list.lzma
		rm -f files.list

		# packages.info.lzma
		PI=packages.info
		_ 'Creating: packages.info.lzma'
		touch $PKGS/$PI
		cd $PKGS; lzma e $PI $PI.lzma
		rm -f $PI

		# Display some info.
		separator
		nb=$(ls $PKGS/*.tazpkg | wc -l)
		time=$(($(date +%s) - $time))
		# L10n: 's' is for seconds (cooking time)
		_ "Packages: \$nb - Time: \${time}s"; newline

		# Create all flavors files at once. Do we really need code to monitor
		# flavors changes? Lets just build them with packages lists before
		# syncing the mirror.
		[ "$2" == "--flavors" ] || exit 1
		[ ! -d "$flavors" ] && (_ "Missing flavors: \$flavors"; newline) && exit 1
		[ -d "$live" ] || mkdir -p $live
		_ "Creating flavors files in: \$live"
		_ "Cook pkgdb: Creating all flavors" | log
		separator
		_ "Recharging lists to use latest packages..."
		tazpkg recharge >/dev/null 2>/dev/null

		# We need a custom tazlito config to set working dir to /home/slitaz.
		if [ ! -f "$live/tazlito.conf" ]; then
			_ "Creating configuration file: tazlito.conf"
			cp /etc/tazlito/tazlito.conf $live
			sed -i s@WORK_DIR=.*@WORK_DIR=\"/home/slitaz\"@ \
				$live/tazlito.conf
		fi

		# Update Hg flavors repo and pack.
		[ -d "$flavors/.hg" ] && cd $flavors && hg pull -u

		cd $live
		_ "Starting to generate flavors..."
		rm -f flavors.list *.flavor
		for i in $flavors/*
		do
			fl=$(basename $i)
			_ "Packing flavor: \$fl"
			tazlito pack-flavor $fl >/dev/null || exit 1
			tazlito show-flavor $fl --brief --noheader 2> \
				/dev/null >> flavors.list
		done
		cp -f $live/*.flavor $live/flavors.list $PKGS
		separator
		fl_size=$(du -sh $live | awk '{print $1}')
		_ "Flavors size: \$fl_size"; newline
		rm -f $command
		separator
		datenow=$(date "$(_ '+%Y-%m-%d %H:%M')")
		_ "Cook pkgdb end: \$datenow" ;;
	*)
		# Just cook and generate a package.
		check_root
		time=$(date +%s)
		pkg="$1"
		[ -z "$pkg" ] && usage
		receipt="$WOK/$pkg/receipt"
		check_pkg_in_wok && newline

		unset inst
		unset_receipt
		. $receipt
		
		# Handle cross compilation.
		case "$ARCH" in
			arm*)
				if [ ! "$HOST_ARCH" ]; then
					_ "cook: HOST_ARCH is not set in \$pkg receipt"
					_ "cook: This package is not included in: \$ARCH"
					[ "$CROSS_BUGS" ] && _ "bugs: \$CROSS_BUGS"
					_ "Cook skip: \$pkg is not included in: \$ARCH" | log
					newline && exit 1
				fi ;;
		esac

		# Some packages are not included in some arch or fail to cross compile.
		: ${HOST_ARCH=i486}
		debug "Host arch $HOST_ARCH"
		# Handle arm{v6hf,v7,..}
		if ! $(echo "$HOST_ARCH" | egrep -q "${ARCH%v[0-9]*}|any"); then
			_ "cook: HOST_ARCH=\$HOST_ARCH"
			_ "cook: \$pkg doesn't cook or is not included in: \$ARCH"
			[ "$CROSS_BUGS" ] && _ "bugs: \$CROSS_BUGS"
			_ "Cook skip: \$pkg doesn't cook or is not included in: \$ARCH" | log
			sed -i /^${pkg}$/d $broken
			newline && exit 0
		fi

		# Skip blocked, 3 lines also for the Cooker.
		if grep -q "^$pkg$" $blocked && [ "$2" != "--unblock" ]; then
			_ "Blocked package: \$pkg"; newline
			 exit 0
		fi

		try_aufs_chroot "$@"

		# Log and source receipt.
		_ "Cook started for: <a href='cooker.cgi?pkg=\$pkg'>\$pkg</a>" | log
		echo "cook:$pkg" > $command

		# Display and log info if cook process stopped.
		# FIXME: gettext not working (in single quotes) here!
		trap '_ "\n\nCook stopped: control-C\n\n" | \
			tee -a $LOGS/$pkg.log' INT

		# Handle --options
		case "$2" in
			--clean|-c)
				_n "Cleaning: \$pkg"
				cd $WOK/$pkg && rm -rf install taz source
				status && newline && exit 0 ;;
			--install|-i)
				inst='yes' ;;
			--getsrc|-gs)
				_ "Getting source for: \$pkg"; separator
				get_source
				_ "Tarball: \$SRC/\$TARBALL"; newline
				exit 0 ;;
			--block|-b)
				_n "Blocking: \$pkg"
				[ $(grep "^$pkg$" $blocked) ] || echo "$pkg" >> $blocked
				status && newline && exit 0 ;;
			--unblock|-ub)
				_n "Unblocking: \$pkg"
				sed -i "/^${pkg}$/"d $blocked
				status && newline && exit 0 ;;
			--pack)
				if [ -d $WOK/$pkg/taz ]; then
					rm -rf $WOK/$pkg/taz
					[ -f $LOGS/$pkg-pack.log ] && rm -rf $LOGS/$pkg-pack.log
					packit 2>&1 | tee -a $LOGS/$pkg-pack.log
					clean_log
				else
					_ "Need to build \$pkg." && exit 0
				fi
				exit 0 ;;
			--cdeps)
				[ ! -d $WOK/$pkg/taz ] && _ "Need to build \$pkg." && exit 0
				_ "Checking depends"; separator
				lddlist=/tmp/lddlist; touch $lddlist
				missing=/var/cache/missing.file
				# find all deps using ldd
				for exe in $(find $WOK/$pkg/taz -type f -perm +111); do
					[ "x$(dd if=$exe bs=4 count=1 2>/dev/null)" == "xELF" ] &&
						ldd $exe | sed 's|	||' | cut -d' ' -f1 >> $lddlist
				done
				# remove exe/so duplicates
				sort -u $lddlist > $lddlist.sorted
				# search packages
				for exefile in $(cat $lddlist.sorted); do
					search_file $exefile
					echo $found >> $lddlist.pkgs
					echo -n "."
				done
				echo
				# remove packages duplicates
				sort -u $lddlist.pkgs > $lddlist.final
				sort -u $missing > $missing.final
				rm -f $lddlist $lddlist.sorted $lddlist.pkgs $missing
				exit 0 ;;
		esac

		# Check if wanted is built now so we have separate log files.
		for wanted in $WANTED ; do
			if grep -q "^$wanted$" $blocked; then
				_ "WANTED package is blocked: \$wanted" | tee $LOGS/$pkg.log
				newline && rm -f $command && exit 1
			fi
			if grep -q "^$wanted$" $broken; then
				_ "WANTED package is broken: \$wanted" | tee $LOGS/$pkg.log
				newline && rm -f $command && exit 1
			fi
			if [ ! -d "$WOK/$wanted/install" ]; then
				cook "$wanted" || exit 1
			fi
		done

		# Cook and pack or exit on error and log everything.
		cookit $@ 2>&1 | loglimit 50 > $LOGS/$pkg.log
		remove_deps | tee -a $LOGS/$pkg.log
		cookit_quality
		packit 2>&1 | loglimit 5 >> $LOGS/$pkg.log
		clean_log

		# Exit if any error in packing.
		lerror=$(_n "ERROR")
		if grep -Ev "(/root/.cvspass|conftest|df: /|rm: can't remove)" $LOGS/$pkg.log | \
		   grep -Eq "(^$lerror|: No such file or directory|not remade because of errors)"; then
			debug_info | tee -a $LOGS/$pkg.log
			rm -f $command && exit 1
		fi

		# Create an XML feed
		gen_rss

		# Time and summary
		time=$(($(date +%s) - $time))
		summary | tee -a $LOGS/$pkg.log
		newline

		# We may want to install/update (outside aufs jail !).
		[ -s /aufs-umount.sh ] ||
		install_package

		# Finally we DON'T WANT to build the *-dev or packages with WANTED="$pkg"
		# You want automation: use the Cooker Build Bot.
		rm -f $command ;;
esac

exit 0
