#!/bin/ash -efu
#
# mki-prepare
#
# This file is part of mkimage
# Copyright (C) 2007-2009  Alexey Gladkov <gladkov.alexey@gmail.com>
#
# This file is covered by the GNU General Public License,
# which should be included with mkimage as the file COPYING.
#

. "${0%/*}"/mki-sh-functions
. "${0%/*}"/mki-sh-image-prepare

verbose "has started executing."

# Instrumental chroot should not have docs.
HSH_EXCLUDE_DOCS=1
IMAGE_INIT_LIST=

run_mkaptbox() {
	rm -rf -- "$pkgbox/aptbox"
	env -i PATH="$PATH" \
	mkaptbox --without-stuff $verbose $quiet $target $apt_config $apt_prefix -- "$pkgbox"
}

if [ ! -d "$pkgbox/aptbox" ]; then
	run_mkaptbox
else
	env -i PATH="$PATH" "$pkgbox"/aptbox/apt-get update ||
		run_mkaptbox # Directory exists, but empty
fi
"$pkgbox"/aptbox/apt-cache --no-generate --names-only --all-names search '' |
	cut -d\  -f1 |
	LANG=C sort -o "$pkgbox"/aptbox/var/cache/pkgnames


verbose "Work directory: $subdir."
[ -d "$chroot" ] ||
	hsh_initroot "$dir"

if [ -n "$CHROOT_PACKAGES" -o -n "$CHROOT_PACKAGES_REGEXP" ]; then
	{
		mki-expand-pkgs simple $CHROOT_PACKAGES &&
		mki-expand-pkgs regexp $CHROOT_PACKAGES_REGEXP ||
			fatal "Unable expand chroot packages"
	} |xargs -r mki-install
fi

ownership="$(stat -c '%u:%g' "$chroot/")" ||
	fatal "$chroot: unable to get ownership."

our="$chroot/.our"
verbose "Output directory for rooter user: $our."
mkdir $verbose -p -m1770 -- "$our"
chown $verbose "$ownership" -- "$our"

verbose "Subwork directory: $subdir."
mkdir $verbose -p -m1770 -- "$subdir"
chown $verbose "$ownership" -- "$subdir"

ln $verbose -nsf -- "$WORKDIRNAME" "$chroot/.image"
