#!/bin/sh -efu
#
# mki-sh-image-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.
#

pkgbox="${PKGBOX:?aptbox required}"
target="${TARGET:+--target="$TARGET"}"
with_qemu="${HSH_USE_QEMU:+--with-qemu="$HSH_USE_QEMU"}"
apt_config="${HSH_APT_CONFIG:+--apt-config="$HSH_APT_CONFIG"}"
apt_prefix="${HSH_APT_PREFIX:+--apt-prefix="$HSH_APT_PREFIX"}"

hsh_initroot() {
	env -i PATH="$PATH" \
	hsh \
		--initroot \
		--without-stuff \
		--pkg-build-list='' \
		--save-fakeroot \
		$verbose $quiet $target $with_qemu $apt_config $apt_prefix \
		${HSH_LANGS:+--install-langs="$HSH_LANGS"} \
		${HSH_NUMBER:+--number="$HSH_NUMBER"} \
		${HSH_EXCLUDE_DOCS:+--excludedocs} \
		${HSH_CACHEDIR:+--cache-dir="$HSH_CACHEDIR"} \
		${IMAGE_INIT_LIST:+--pkg-init-list="$IMAGE_INIT_LIST"} \
		-- "$1" ||
	fatal "$1: unable to make initial chroot: rc=$?"

	local pkgs="${PACKAGES_REQUIRED_INITROOT:-}"
	if [ -n "$pkgs" ]; then
		env -i PATH="$PATH" \
		hsh-install \
			$verbose $quiet \
			${HSH_NUMBER:+--number="$HSH_NUMBER"} \
			${HSH_EXCLUDE_DOCS:+--excludedocs} \
			-- "$1" $pkgs ||
		fatal "$1: unable to install packages: rc=$?"
	fi

	# Create missing objects in hasher root's /dev.
	[ -d "$1"/chroot/dev/shm ] ||
		install -d -m1777 "$1"/chroot/dev/shm
	[ -d "$1"/chroot/dev/pts ] ||
		install -d -m755 "$1"/chroot/dev/pts
	[ -L "$1"/chroot/dev/fd ] ||
		ln -s /proc/self/fd "$1"/chroot/dev/fd
	[ -L "$1"/chroot/dev/stdin ] ||
		ln -s /proc/self/fd/0 "$1"/chroot/dev/stdin
	[ -L "$1"/chroot/dev/stdout ] ||
		ln -s /proc/self/fd/1 "$1"/chroot/dev/stdout
	[ -L "$1"/chroot/dev/stderr ] ||
		ln -s /proc/self/fd/2 "$1"/chroot/dev/stderr

	printf "%s\n" \
		"666 /dev/null c 1 3" \
		"666 /dev/zero c 1 5" \
		"666 /dev/full c 1 7" \
		"644 /dev/random c 1 8" \
		"644 /dev/urandom c 1 9" \
		"600 /dev/console c 5 1" \
		"600 /dev/tty0 c 4 0" \
		"666 /dev/tty c 5 0" \
		"666 /dev/ptmx c 5 2" |
	while read mode name type major minor ; do
		[ ! -e "$1/chroot/$name" ] ||
			continue
		mki-fakedev \
			$verbose $quiet \
			-o root \
			-m "$mode" \
			-- "$1" "$name" "$type" "$major" "$minor" ||
		fatal 'Failed to create essential devices.'
	done

	if [ ! -e "$1"/chroot/dev/pts/ptmx ]; then
		mv "$1"/chroot/dev/ptmx "$1"/chroot/dev/pts/ptmx
		ln -s pts/ptmx "$1"/chroot/dev/ptmx
	fi

	rm -rf -- "$1/repo" "$1/chroot/.out"
}
