#!/bin/sh -e

divert() {
  prog="$1"
  mv $prog $prog.real
  cat > $prog <<EOF
#!/bin/sh

echo "Fake $prog called, doing nothing"
EOF
  chmod 755 $prog
}

undivert() {
  prog="$1"
  mv $prog.real $prog
}


DEBIAN_FRONTEND=noninteractive
export DEBIAN_FRONTEND

# set root password - We can't do this through base-config because the
# passwd .config script clears the database before asking for the
# password

if [ -n "$root_password" ]; then
    chroot $TARGET chpasswd <<EOF
root:$root_password
EOF
fi

# apt-setup insists on invoking clear(1)
TERM=vt100
export TERM
# let apt-setup believe we're editing sources.list by hand; we already set it up
EDITOR=touch
export EDITOR

if ! test -x $TARGET/usr/bin/debconf-set-selections; then
    echo "debconf is too old for us to seed the database; not running base-config"
    exit 0
fi

# avoid base-config if it's missing, which happens to
# be te case for older-than-sarge debian
# The module name is misleading 
if [ -x "$TARGET/usr/sbin/base-config" ] ; then

	chroot $TARGET debconf-set-selections <<EOF
passwd passwd/make-user boolean false
base-config apt-setup/uri_type text edit sources list by hand
base-config base-config/menu/pkgsel select nothing - you may manually run apt-get or any of the above later
EOF

	chroot $TARGET mount -t proc proc /proc
	divert $TARGET/sbin/start-stop-daemon
	chroot $TARGET base-config
	undivert $TARGET/sbin/start-stop-daemon
	chroot $TARGET umount /proc
	# kill any processes using the target fs
	fuser -k -v -m $TARGET || true
else
	echo "'base-config' not found, skipping."
fi

