#!/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"
export output=raw


# Internationalization.

export TEXTDOMAIN='cook'


#
# Functions
#

usage() {
	cat <<EOT

$(boldify "$(_ 'Usage:')") $(_ 'cook [package|command] [list|--option]')

$(boldify "$(_ 'Commands:')")
  usage|help           $(_ 'Display this short usage.')
  setup                $(_ 'Setup your build environment.')
  *-setup              $(_ 'Setup a cross environment.')
                       * = {arm|armv6hf|armv7|x86_64}
  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.')

$(boldify "$(_ 'Options:')")
cook <pkg>
    --clean       -c   $(_ 'clean the package in the wok.')
    --install     -i   $(_ 'cook and install the package.')
    --getsrc      -gs  $(_ 'get the package source tarball.')
    --block       -b   $(_ 'block a package so cook will skip it.')
    --unblock     -ub  $(_ 'unblock a blocked package.')
    --cdeps            $(_ 'check dependencies of cooked package.')
    --pack             $(_ 'repack an already built package.')
    --debug            $(_ 'display debugging messages.')
    --continue         $(_ 'continue running compile_rules.')
cook new <pkg>
    --interactive -x   $(_ 'create a receipt interactively.')
cook setup
    --wok              $(_ 'clone the cooking wok from Hg repo.')
    --stable           $(_ 'clone the stable wok from Hg repo.')
    --undigest         $(_ 'clone the undigest wok from Hg repo.')
    --tiny             $(_ 'clone the tiny SliTaz wok from Hg repo.')
    --forced           $(_ 'force reinstall of chroot packages.')
cook pkgdb
    --flavors          $(_ '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 "%s" in the wok' "$pkg"; newline
		exit 1
	fi
}


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


# Initialize files used in $CACHE

init_db_files() {
	_ 'Creating directories structure in "%s"' "$SLITAZ"
	mkdir -p $WOK $PKGS $SRC $CACHE $LOGS $FEEDS
	_ 'Creating DB files in "%s"' "$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)
				value="${value:-empty}"
				valid="$(echo $PKGS_CATEGORIES)" # avoid newlines
				if ! echo " $valid " | grep -q " $value "; then
					_ 'QA: unknown category "%s"' "$value"
					longline "$(_ 'Please, use one of: %s' "$valid")"
					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 "%s"' "$value"
				fi ;;
		esac
	done
}


# Paths used in receipt and by cook itself.

set_paths() {
	pkgdir="$WOK/$PACKAGE"
	. "$pkgdir/receipt"
	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 [ -n "$PATCH" ]; then
		[ -z "$PTARBALL" ] && PTARBALL="$(basename $PATCH)"
	fi
	if [ -n "$WANTED" ]; then
		basesrc="$WOK/$WANTED/source"
		src="$basesrc/$WANTED-$VERSION"
		install="$WOK/$WANTED/install"
		wanted_stuff="$WOK/$WANTED/stuff"
	fi
	if [ -n "$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\" -f2)
		kbasevers=${kvers:0:3}
	elif [ -f "$INSTALLED/linux-api-headers/receipt" ]; then
		kvers=$(grep ^VERSION= $INSTALLED/linux-api-headers/receipt | cut -d\" -f2)
		kbasevers=${kvers:0:3}
	fi
	# Python version
	if [ -f "$WOK/python/receipt" ]; then
		pyvers=$(grep ^VERSION= $WOK/python/receipt | cut -d\" -f2)
	fi
	# Perl version for some packages needed it
	if [ -f "$WOK/perl/receipt" ]; then
		perlvers=$(grep ^VERSION= $WOK/perl/receipt | cut -d\" -f2)
	fi
	# Old way compatibility.
	_pkg="$install"
}


# Create source tarball when URL is a SCM.

create_tarball() {
	local tarball
	tarball="$pkgsrc.tar.bz2"
	[ -n "$LZMA_SRC" ] && tarball="$lzma_tarball"
	_ 'Creating tarball "%s"' "$tarball"
	if [ -n "$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: %s' "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: %s' "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 %s...' 'Hg'
			_ 'URL: %s' "$url"
			_ 'Cloning to "%s"' "$pwd/$pkgsrc"
			if [ -n "$BRANCH" ]; then
				_ 'Hg branch: %s' "$BRANCH"
				hg clone $url --rev $BRANCH $pkgsrc || \
					(_ 'ERROR: %s' "hg clone $url --rev $BRANCH" && exit 1)
			else
				hg clone $url $pkgsrc || (_ 'ERROR: %s' "hg clone $url" && exit 1)
			fi
			rm -rf $pkgsrc/.hg
			create_tarball ;;

		git*)
			url=${WGET_URL#git|}
			_ 'Getting source from %s...' 'Git'
			_ 'URL: %s' "$url"
			cd $SRC
			git clone $url $pkgsrc || (_ 'ERROR: %s' "git clone $url" && exit 1)
			if [ -n "$BRANCH" ]; then
				_ 'Git branch: %s' "$BRANCH"
				cd $pkgsrc; git checkout $BRANCH; cd ..
			fi
			cd $SRC
			create_tarball ;;

		cvs*)
			url=${WGET_URL#cvs|}
			mod=$PACKAGE
			[ -n "$CVS_MODULE" ] && mod=$CVS_MODULE
			_ 'Getting source from %s...' 'CVS'
			_ 'URL: %s' "$url"
			[ -n "$CVS_MODULE" ] && _ 'CVS module: %s' "$mod"
			_ 'Cloning to "%s"' "$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 %s...' 'SVN'
			_ 'URL: %s' "$url"
			if [ -n "$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 %s...' 'bazaar'
			cd $SRC
			pkgsrc=${url#*:}
			if [ -n "$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 -e "BRANCH=\"$BRANCH\"\n"
			fi
			mv $pkgsrc $pkgsrc-$BRANCH
			pkgsrc="$pkgsrc-$BRANCH"
			create_tarball ;;

		*)
			(newline; _ 'ERROR: Unable to handle "%s"' "$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 %s...' 'mirror'
		_ 'URL: %s' "$url"
		busybox wget -c -P $SRC $url || _ 'ERROR: %s' "wget $url"
	fi
	_ 'Extracting source archive "%s"' "$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 2>/dev/null >&2 ;;
		*.Z|*.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 time.

disp_time() {
	local sec div min
	sec="$1"
	div=$(( ($1 + 30) / 60))
	case $div in
		0) min='';;
		# L10n: 'm' is for minutes (approximate cooking time)
		*) min=$(_n ' ~ %dm' "$div");;
	esac

	# L10n: 's' is for seconds (cooking time)
	_ '%ds%s' "$sec" "$min"
}


# Display cooked package summary.

summary() {
	set_paths
	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=$(ls -lh $PKGS/$pkg-${VERSION}*.tazpkg | awk '{print $5}')
	files=$(cat $WOK/$pkg/taz/$pkg-*/files.list | wc -l)
	[ -n "$TARBALL" ] && srcsize=$(du -sh $SRC/$TARBALL | awk '{print $1}')

	_ 'Summary for: %s' "$PACKAGE $VERSION"
	separator

	# L10n: keep the same width of translations to get a consistent view
	[ -n "$srcdir" ]  && _ 'Source dir  : %s' "$srcdir"
	[ -n "$TARBALL" ] && _ 'Src file    : %s' "$TARBALL"
	[ -n "$srcsize" ] && _ 'Src size    : %s' "$srcsize"
	[ -n "$prod" ]    && _ 'Produced    : %s' "$prod"
	_ 'Packed      : %s' "$fs"
	_ 'Compressed  : %s' "$size"
	_ 'Files       : %s' "$files"
	_ 'Cook time   : %s' "$(disp_time "$time")"
	_ 'Cook date   : %s' "$(date "$(_ '+%%F %%R')")"
	_ 'Host arch   : %s' "$ARCH"
	separator
}


# Display debugging error info.

debug_info() {
	title 'Debug information'
	# L10n: specify your format of date and time (to help: man date)
	# L10n: not bad one is '+%x %R'
	_ 'Cook date: %s' "$(date "$(_ '+%%F %%R')")"
	[ "$time" ] && _ 'Cook time: %ds' "$(($(date +%s) - $time))"
	# 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' \
		'Could not read symbols: File in wrong format'
	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
	footer
}


# A bit smarter function than the classic `cp` command

copy() {
	if [ "$(stat -c %h -- "$1")" -gt 1 ]; then
		cp -al "$1" "$2"	# copy hardlinks
	else
		cp -a  "$1" "$2"	# copy generic files
	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.

copy_generic_files() {
	# $LOCALE is set in cook.conf
	if [ -n "$LOCALE" -a -z "$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
					copy $install/usr/share/locale/$i $fs/usr/share/locale
				fi
			done
		fi
	fi

	# Generic pixmaps copy can be disabled with COOKOPTS="!pixmaps" (or GENERIC_PIXMAPS="no")
	if [ "${COOKOPTS/!pixmaps/}" == "$COOKOPTS" -a "$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
				copy $install/usr/share/pixmaps/$PACKAGE.png \
					$fs/usr/share/pixmaps
			elif [ -f "$install/usr/share/pixmaps/$PACKAGE.xpm" ]; then
				copy   $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
			copy $stuff/$PACKAGE.png $fs/usr/share/pixmaps
		fi
	fi

	# Desktop entry (.desktop).
	# Generic desktop entry copy can be disabled with COOKOPTS="!menus" (or GENERIC_MENUS="no")
	if [ "${COOKOPTS/!menus/}" == "$COOKOPTS" -a "$GENERIC_MENUS" != 'no' ]; then
		if [ -d "$install/usr/share/applications" ] && [ -z "$WANTED" ]; then
			mkdir -p $fs/usr/share
			copy $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
		copy $stuff/applications $fs/usr/share
	fi
	if [ -f "$stuff/$PACKAGE.desktop" ]; then
		mkdir -p $fs/usr/share/applications
		copy $stuff/$PACKAGE.desktop $fs/usr/share/applications
	fi

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


# Remove files provided by split packages
# For example:
#   1. Package "pkg-main":
#      SPLIT="pkg-1 pkg-2 pkg-extra"
#   2. Package="pkg-extra":
#      WANTED="pkg-main"
#      BUILD_DEPENDS="pkg-1 pkg-2"
#      cook_copy_folders usr
#      cook_split_rm $BUILD_DEPENDS

cook_split_rm() {
	for i in $@; do
		action 'Remove files provided by split package %s...' "$i"
		while read j; do
			[ -f "$fs$j" -o -h "$fs$j" ] && rm $fs$j
			rmdir "$(dirname "$fs$j")" 2>/dev/null
		done < $WOK/$i/taz/$i-$VERSION/files.list
		:; status
	done
}


# Update installed.cook.diff

update_installed_cook_diff() {
	# If a cook failed deps are removed.
	cd $root$INSTALLED; ls -1 > $CACHE/installed.cook
	cd $CACHE
	[ "$1" == 'force' -o ! -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)
}


# 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"
		[ -n "$root" ] && echo "root=\"$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 | fold -sw80
}


# The main cook function.

cookit() {
	if [ -n "$SETUP_MD5" ] && [ "$SETUP_MD5" != "$(ls $root$INSTALLED | \
			md5sum | cut -c1-32)" ]; then
		_ 'ERROR: Broken setup. Abort.'
		return
	fi

	title 'Cook: %s' "$PACKAGE $VERSION"
	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"
			_ '%s sysroot: %s' "$ARCH" "$sysroot"
			_ 'Adding "%s" to PATH' "$tools/bin"
			export PATH="$PATH:$tools/bin"
			export PKG_CONFIG_PATH="$sysroot/usr/lib/pkgconfig"
			export CROSS_COMPILE="$HOST_SYSTEM-"
			_ 'Using cross-tools: %s' "$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

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

	# Disable -pipe if less than 512 MB free RAM.
	free=$(awk '/^MemFree|^Buffers|^Cached/{s+=$2}END{print int(s/1024)}' /proc/meminfo)
	if [ "$free" -lt 512 ] && [ "$CFLAGS" != "${CFLAGS/-pipe}" ]; then
		_ 'Disabling -pipe compile flag: %d MB RAM free' "$free"
		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
	[ -n "$BUILD_DEPENDS" ] && _ 'Checking build dependencies...'
	[ -n "$root" ] && _ 'Using packages DB: %s' "$root$DB"
	for dep in $BUILD_DEPENDS; do
		implicit="${dep%-dev}"
		# Don't add implicit dependency if it defined in DEPENDS
		# echo '' $DEPENDS '' | fgrep -q " $implicit " && implicit=''
		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 [ -z "$vers" ]; then
					vers=$(awk -F$'\t' -vp="$i" '$1==p{print $2; quit}' $PKGS/packages.info 2> /dev/null)
				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 [ -n "$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): %s' "$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 "%s"' "$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" ] && [ -n "$AUTO_COOK" ]; then
		_ 'Auto cook config is set: %s' "$AUTO_COOK"
		cp -f $LOGS/$PACKAGE.log $LOGS/$PACKAGE.log.$$
		for i in $(uniq $CACHE/missing.dep); do
			(_ 'Building dep (wok/pkg)    : %s' "$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 \"%s\"" "$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)
		_p 'ERROR: missing %d dependency' 'ERROR: missing %d dependencies' "$nb" "$nb"
		exit 1
	fi

	# Install local packages: package-version$arch
	cd $PKGS
	for i in $(uniq $CACHE/installed.local); do
		# _ 'Installing dep (pkg/local): %s' "$i"
		tazpkg install $i --root=$root --local --quiet --cookmode
	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): %s' "$i"
		tazpkg get-install $i --root=$root --quiet --cookmode
	done

	update_installed_cook_diff

	# 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 [ -n "$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 [ -z "$WANTED" ] && [ -n "$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 [ -n "$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: %s' '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

	# Actions to do after compiling the package
	# Skip all for split packages (already done in main package)
	if [ -z "$WANTED" ]; then
		footer
		export COOKOPTS ARCH install; @@PREFIX@@/libexec/cookutils/compressor install
	fi
	footer

	# Execute testsuite.
	if grep -q ^testsuite $receipt; then
		title 'Running testsuite'
		testsuite $@ || exit 1
		footer
	fi

	update_installed_cook_diff force
}


# Cook quality assurance.

cookit_quality() {
	if [ ! -d "$WOK/$pkg/install" ] && [ -z "$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

	title 'Pack: %s' "$PACKAGE $VERSION$arch"

	if grep -q ^genpkg_rules $receipt; then
		_ 'Executing: %s' '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

	# Check CONFIG_FILES
	if [ -n "$CONFIG_FILES" ]; then
		for i in $CONFIG_FILES; do
			if [ ! -e $fs$i ]; then
				case $i in
					*/) mkdir -p $fs$i ;;
					*)  mkdir -p $fs$(dirname $i); touch $fs$i ;;
				esac
			fi
		done
	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
		action 'Copying "%s"...' "$file"
		cp -f ../$file $pack; chown 0.0 $pack/$file; status
	done
	copy_generic_files

	# Strip and stuff files.
	export COOKOPTS ARCH HOST_SYSTEM LOCALE fs; @@PREFIX@@/libexec/cookutils/compressor fs

	# Create files.list with redirecting find output.
	action '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

	# Md5sum of files.
	action '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 'END{ print $1 }')

	# Build cpio archives.
	action 'Compressing the FS...'
	find fs -newer $receipt -exec touch -hr $receipt {} \;
	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 'END{ print $1 }')

	action '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 [ -n "$EXTRAVERSION" ]; then
		action 'Updating receipt EXTRAVERSION: %s' "$EXTRAVERSION"
		sed -i s/^EXTRAVERSION.*$// receipt
		sed -i "s/^VERSION=/EXTRAVERSION=\"$EXTRAVERSION\"\nVERSION=/" receipt
		status
	fi

	# Compress.
	action 'Creating full cpio archive...'
	find . -print | cpio -o -H newc --quiet > \
		../$PACKAGE-$VERSION$EXTRAVERSION$arch.tazpkg
	status

	action '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
	footer "$(_ 'Package "%s" created' "$tazpkg")"
}


# Verify package quality and consistency.

packit_quality() {
	#action '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

	action 'QA: checking for empty package...'
	files=$(cat $WOK/$pkg/taz/$pkg-*/files.list | wc -l)
	if [ "$files" -eq 0 -a "$CATEGORY" != 'meta' ]; then
		newline; _ 'ERROR: empty package'
		rm -f $command
		exit 1
	else
		:; status
		# Find and remove old package(s)
		tempd="$(mktemp -d)"; cd "$tempd"
		for testpkg in $(ls $PKGS/$pkg-*.tazpkg 2> /dev/null); do
			# Extract receipt from each matched package
			cpio -F "$testpkg" -i receipt >/dev/null 2>&1
			name=$(. receipt; echo $PACKAGE)
			rm receipt
			if [ "$name" == "$pkg" ]; then
				action 'Removing old package "%s"' "$(basename "$testpkg")"
				rm -f "$testpkg"
				status
			fi
		done
		rm -r "$tempd"
		mv -f $pkgdir/taz/$pkg-*.tazpkg $PKGS
		sed -i /^${pkg}$/d $broken
		#action 'Removing source tree...'
		#rm -f $WOK/$pkg/source; status
	fi
}


# Reverse "cat" command: prints input lines in the reverse order

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- -f1)
	if [ -n "$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 %s chroot environment...' "$ARCH"
		_ 'Updating chroot: %s' "$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
	grep -q ^aufs /proc/modules || 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 mount 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
}


# Encode predefined XML entities

xml_ent() {
	sed -e 's|&|\&amp;|g; s|<|\&lt;|g; s|>|\&gt;|g; s|"|\&quot;|g' -e "s|'|\&apos;|g"
}


# 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>$(echo -n "$SHORT_DESC" | xml_ent)</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 [ -n "$(busybox cpio --to-stdout --quiet -i files.list < $package | \
			grep /$srch\$)" ]; 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:'; echo "$multiples"; newline
	_ 'Select one [%s]: ' "$first"; read my_choice
	found="${my_choice:-$first}"
}


# 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$'\t' -f2)
	if [ -z "$found" ]; then
		found=$(search_file_local $srch)
		if [ -n "$found" ]; then
			if [ $(echo "$found" | wc -l) -gt 1 ]; then
				ask_multiple "$found"
			fi
			echo -e "$srch\t$found" >> $cache
		else
			found=$(search_file_mirror $srch)
			if [ -n "$found" ]; then
				if [ $(echo "$found" | wc -l) -gt 1 ]; then
					ask_multiple "$found"
				fi
				echo -e "$srch\t$found" >> $cache
			else
				echo "$srch" >> $missing
			fi
		fi
	fi
}


#
# Receipt functions to ease packaging
#

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


# Function to use in compile_rules() to copy man page from $src to $install

cook_pick_manpages() {
	local name section
	action 'Copying man pages...'

	for i in $@; do
		name=$(echo $i | sed 's|\.[gbx]z2*$||')
		section=${name##*/}; section=${section##*.}
		mkdir -p $install/usr/share/man/man$section
		copy $i  $install/usr/share/man/man$section
	done
	status
}


# Function to use in genpkg_rules() to copy specified files from $install to $fs

cook_copy_files() {
	action 'Copying files...'
	cd $install
	local i j
	IFS=$'\n'
	for i in $@; do
		for j in $(find . -name $i ! -type d); do
			mkdir -p  $fs$(dirname ${j#.})
			copy $j $fs$(dirname ${j#.})
		done
	done
	cd - >/dev/null
	status
}


# Function to use in genpkg_rules() to copy specified folders from $install to $fs

cook_copy_folders() {
	action 'Copying folders...'
	cd $install
	local i j
	IFS=$'\n'
	for i in $@; do
		for j in $(find . -name $i -type d); do
			mkdir -p  $fs$(dirname ${j#.})
			copy $j $fs$(dirname ${j#.})
		done
	done
	cd - >/dev/null
	status
}


# Function to use in genpkg_rules() to copy hicolor icons in specified sizes
# (default: 16 and 48) from $install to $fs

cook_copy_icons() {
	local sizes=$@
	action 'Copying hicolor icons...'
	mkdir -p $fs/usr/share/icons/hicolor
	for i in ${sizes:-16 48}; do
		[ ! -e "$install/usr/share/icons/hicolor/${i}x$i" ] ||
		copy $install/usr/share/icons/hicolor/${i}x$i \
			$fs/usr/share/icons/hicolor
	done
	status
}




#
# Commands
#

case "$1" in
	usage|help|-u|-h)
		 usage ;;

	list-wok)
		title 'List of %s packages in "%s"' "$ARCH" "$WOK"
		cd $WOK
		if [ "$ARCH" != 'i486' ]; then
			count=0
			for pkg in $(fgrep 'HOST_ARCH=' */receipt | egrep "$ARCH|any" | cut -d: -f1)
			do
				unset HOST_ARCH
				. $pkg
				count=$(($count + 1))
				colorize 34 "$PACKAGE"
			done
		else
			count=$(ls | wc -l)
			ls -1
		fi
		footer "$(_p '%s package' '%s packages' "$count" "$(colorize 32 "$count")")"
		;;

	activity)
		cat $activity ;;

	search)
		# Just a simple search function, we dont need more actually.
		query="$2"
		title 'Search results for "%s"' "$query"
		cd $WOK; ls -1 | grep "$query"
		footer ;;

	setup)
		# Setup a build environment
		check_root
		_ 'Cook: setup environment' | log
		title 'Setting up your environment'
		[ -d $SLITAZ ] || mkdir -p $SLITAZ
		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: %s is not installed' 'cross'
					exit 1
				fi
				_ 'Using config file: %s' '/etc/slitaz/cross.conf'
				. /etc/slitaz/cross.conf ;;
		esac
		for pkg in $SETUP_PKGS; do
			if [ -n "$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 "%s"' 'slitaz'
			addgroup slitaz
		fi
		_ 'Setting permissions for group "%s"...' 'slitaz'
		find $SLITAZ -maxdepth 2 -exec chown root.slitaz {} \;
		find $SLITAZ -maxdepth 2 -exec chmod g+w {} \;
		footer "$(_ 'All done, ready to cook packages :-)')" ;;

	*-setup)
		# Setup for cross compiling.
		arch="${1%-setup}"
		check_root
		. /etc/slitaz/cook.conf
		for pkg in $CROSS_SETUP; do
			if [ -n "$forced" ]; then
				tazpkg -gi $pkg --forced
			else
				[ ! -d "$INSTALLED/$pkg" ] && tazpkg -gi $pkg
			fi
		done

		_ 'Cook: setup %s cross environment' "$arch" | log
		title 'Setting up your %s cross environment' "$arch"
		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     : %s' "$ARCH"
		_ 'Configure args  : %s' "$CONFIGURE_ARGS"
		_ 'Build flags     : %s' "$flags"
		_ 'Arch sysroot    : %s' "$sysroot"
		_ 'Tools prefix    : %s' "$tools/bin"
		# Tell the packages manager where to find packages.
		_ 'Packages DB     : %s' "$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: %s is not installed in sysroot' '(e)glibc-base')
		fi
		# Show GCC version or warn if not yet compiled.
		if [ -x "$tools/bin/$HOST_SYSTEM-gcc" ]; then
			_ 'Cross compiler  : %s' "$HOST_SYSTEM-gcc"
		else
			colorize 36 $(_ 'C compiler "%s" is missing' "$HOST_SYSTEM-gcc")
			_ 'Run "%s" to cook a toolchain' 'cross compile'
		fi
		footer ;;

	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"
		[ -z "$pkg" ] && usage
		newline
		if [ -d "$WOK/$pkg" ]; then
			_ 'Package "%s" already exists.' "$pkg"
			exit 1
		fi

		action 'Creating folder "%s"' "$WOK/$pkg"
		mkdir $WOK/$pkg; cd $WOK/$pkg; status

		action '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       : %s' "$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=.*|WGET_URL=\"$answer\"|" receipt

				# Ask for a stuff dir.
				confirm "$(_n 'Do you need a stuff directory? (y/N)')"
				if [ "$?" -eq 0 ]; then
					action 'Creating the stuff directory...'
					mkdir $WOK/$pkg/stuff; status
				fi

				# Ask for a description file.
				confirm "$(_n 'Are you going to write a description? (y/N)')"
				if [ "$?" -eq 0 ]; then
					action 'Creating the "%s" file...' 'description.txt'
					touch $WOK/$pkg/description.txt; status
				fi

				footer "$(_ 'Receipt is ready to use.')" ;;
		esac ;;

	list)
		# Cook a list of packages (better use the Cooker since it will order
		# packages before executing cook).
		check_root
		if [ -z "$2" ]; then
			newline; _ 'No list in argument.'; newline
			exit 1
		fi
		if [ ! -f "$2" ]; then
			newline; _ 'List "%s" not found.' "$2"; newline
			exit 1
		fi

		_ 'Starting cooking the list "%s"' "$2" | log

		for pkg in $(cat $2); do
			cook $pkg || broken
		done ;;

	clean-wok)
		check_root
		newline; action 'Cleaning all packages files...'
		rm -rf $WOK/*/taz $WOK/*/install $WOK/*/source
		status; newline ;;

	clean-src)
		check_root
		newline; action 'Cleaning all packages sources...'
		rm -rf $WOK/*/source
		status; newline ;;

	uncook)
		cd $WOK
		count=0
		title 'Checking for uncooked packages'

		for pkg in *; do
			unset HOST_ARCH EXTRAVERSION
			[ ! -e $pkg/receipt ] && continue
			. $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 "%s"' "$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
			footer "$(_p '%s uncooked package' '%s uncooked packages' "$count" "$(colorize 31 "$count")")"
		else
			_ 'All packages are cooked :-)'
			newline
		fi
		;;

	pkgdb)
		# Create suitable packages list for TazPkg and only for built packages
		# as well as flavors files for TazLiTo. We don't need logs since we do it
		# manually to ensure everything is fine before syncing the mirror.
		@@PREFIX@@/libexec/cookutils/pkgdb "$2"
		;;

	*)
		# Just cook and generate a package.
		check_root
		time=$(date +%s)
		pkg="$1"
		[ -z "$pkg" ] && usage
		lastcooktime=$(sed '/^Cook time/!d;s|.*: *\([0-9]*\)s.*|\1|' \
				$LOGS/$pkg.log 2> /dev/null | sed '$!d')
		receipt="$WOK/$pkg/receipt"
		check_pkg_in_wok
		newline

		unset inst
		unset_receipt
		. $receipt

		# Handle cross compilation.
		case "$ARCH" in
			arm*)
				if [ -z "$HOST_ARCH" ]; then
					_ 'cook: HOST_ARCH is not set in "%s" receipt' "$pkg"
					error="$(_ 'package "%s" is not included in %s' "$pkg" "$ARCH")"
					_ 'cook: %s' "$error"
					[ -n "$CROSS_BUGS" ] && _ 'bugs: %s' "$CROSS_BUGS"
					_ 'Cook skip: %s' "$error" | 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 %s' "$HOST_ARCH")"
		# Handle arm{v6hf,v7,..}
		if ! $(echo "$HOST_ARCH" | egrep -q "${ARCH%v[0-9]*}|any"); then
			_ 'cook: %s' "HOST_ARCH=$HOST_ARCH"
			error="$(_ "package \"%s\" doesn't cook or is not included in %s" "$pkg" "$ARCH")"
			_ 'cook: %s' "error"
			[ -n "$CROSS_BUGS" ] && _ 'bugs: %s' "$CROSS_BUGS"
			_ 'Cook skip: %s' "$error" | 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
			_ 'Package "%s" is blocked' "$pkg"; newline
			exit 0
		fi

		try_aufs_chroot "$@"

		# Log and source receipt.
		_ 'Cook started for: %s' "<a href='cooker.cgi?pkg=$pkg'>$pkg</a>" | log
		echo "cook:$pkg" > $command
		[ "$lastcooktime" ] &&
		echo "cook:$pkg $lastcooktime $(date +%s)" >> $cooktime
		while read cmd duration start; do
			[ $(($start + $duration)) -lt $(date +%s) ] &&
			echo "sed -i '/^$cmd $duration/d' $cooktime"
		done < $cooktime | sh

		# 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)
				action 'Cleaning "%s"' "$pkg"
				cd $WOK/$pkg; rm -rf install taz source
				status; newline
				exit 0 ;;

			--install|-i)
				inst='yes' ;;

			--getsrc|-gs)
				title 'Getting source for "%s"' "$pkg"
				get_source
				_ 'Tarball: %s' "$SRC/$TARBALL"; newline
				exit 0 ;;

			--block|-b)
				action 'Blocking package "%s"' "$pkg"
				[ $(grep "^$pkg$" $blocked) ] || echo "$pkg" >> $blocked
				status; newline
				exit 0 ;;

			--unblock|-ub)
				action 'Unblocking package "%s"' "$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 "%s"' "$pkg"
					exit 0
				fi
				exit 0 ;;

			--cdeps)
				if [ ! -d $WOK/$pkg/taz ]; then
					_ 'Need to build "%s"' "$pkg"
					exit 0
				fi

				title 'Checking depends'
				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

		# Rotate log
		for i in $(seq 9 -1 1); do
			j=$(($i - 1))
			[ -e $LOGS/$pkg.log.$j ] && mv -f $LOGS/$pkg.log.$j $LOGS/$pkg.log.$i
		done
		[ -e $LOGS/$pkg.log ] && mv $LOGS/$pkg.log $LOGS/$pkg.log.0

		# 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 "%s" is blocked' "$wanted" | tee $LOGS/$pkg.log
				newline
				rm -f $command
				exit 1
			fi
			if grep -q "^$wanted$" $broken; then
				_ 'WANTED package "%s" 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|ake: \*\*\* .* Error)"; 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
