#!/bin/sh

# Author : Benoit PAPILLAULT <benoit.papillault@free.fr>
# Creation : 23/08/2004

# This script properly enters the stage3 chroot env.

. config
. config-auto

TOOLS="/tmp/tools2"

# create the HOME dir for root account
mkdir -p "${IMAGE}/root"

# mount /dev, /dev/pts & /proc
mount --bind /dev "${IMAGE}/dev" &&
mount --bind /dev/pts "${IMAGE}/dev/pts" &&
mount --bind /proc "${IMAGE}/proc" &&

# create /dev/stdin /dev/stdout /dev/stderr
ln -sf /proc/self/fd "${IMAGE}/dev" &&
ln -sf fd/0 "${IMAGE}/dev/stdin" &&
ln -sf fd/1 "${IMAGE}/dev/stdout" &&
ln -sf fd/2 "${IMAGE}/dev/stderr" &&

# mount /tmp/.X11-unix to have X11 access to the host
if [ -n "${DISPLAY}" ]; then
  mkdir -p "${IMAGE}/tmp/.X11-unix" &&
  mount --bind /tmp/.X11-unix "${IMAGE}/tmp/.X11-unix"
  V_DISPLAY="DISPLAY=${DISPLAY}"
  # give access to any clients (might be a security risk)
  # xhost + (does not work... since we are root)
fi

# check if target tools are installed (spell coreutils)
if [ -x "${IMAGE}/bin/env" ]; then
	chroot "${IMAGE}" /bin/env -i \
	HOME=/root TERM=$TERM PS1='\u:\w\$ ' \
	PATH=/bin:/sbin:/usr/bin:/usr/sbin \
	${V_DISPLAY} \
	/bin/bash --login
else
	chroot "${IMAGE}" "${TOOLS}/bin/env" -i \
	HOME=/root TERM=$TERM PS1='\u:\w\$ ' \
	PATH="/bin:/sbin:/usr/bin:/usr/sbin:${TOOLS}/bin:${TOOLS}/sbin" \
	${V_DISPLAY} \
	"${TOOLS}/bin/bash" --login
fi

# umount /tmp/.X11 (if needed)
if [ -n "${DISPLAY}" ]; then
  umount "${IMAGE}/tmp/.X11-unix"
fi

umount "${IMAGE}/proc"
umount "${IMAGE}/dev/pts"
umount "${IMAGE}/dev"
