#!/bin/sh -e
# This program handles debian's second stage install -- after installing
# the base system and rebooting, the inittab runs this program.

if [ -x /usr/bin/script -a -z "$BASE_CONFIG_IN_SCRIPT" ]; then
	# We want this program to run inside script. So if it's not already
	# running, run script.
	export BASE_CONFIG_IN_SCRIPT=1 
	SHELL=$0 exec script -q -a /var/log/installer.log
	exit 1 # never reached
fi
SHELL=/bin/sh
export SHELL

echo "Configuring the base system..."

cleanup () {
	cd /
	if [ "$TMPDIR" ]; then
		rm -rf $TMPDIR
	fi
	exit
}

if [ -e /root/dbootstrap_settings ]; then
	# Trap most signals because a ctrl-c killing base-config
	# in the middle of the second stage install would be bad.
	trap "" 1 2 3 15
else 
	# Just trap ctrl-c, and cleanly exit.
	trap cleanup 2
fi

# Copy the base-config scripts into a temp directory. This is done so if
# base-config removes itself, the run-parts still finds all the scripts.
TMPDIR=/tmp/base-config.$$
mkdir $TMPDIR
cp -a /usr/lib/base-config/* $TMPDIR

# If this is a new install, pass "new" as the first parameter to each
# script.
if [ -e /root/dbootstrap_settings ]; then
	PARAM=new
fi

# Run each script. Check return codes, and if they are >= 10,
# jump to the script matching the code.
cd $TMPDIR
# That trailing space is important.
SCRIPTS="$(echo $(find * -type f -regex '[-_A-Za-z0-9]*' | sort -n)) "
ORIGSCRIPTS="$SCRIPTS"
while [ ! -z "$SCRIPTS" ]; do
        script=${SCRIPTS%% *}
	SCRIPTS=${SCRIPTS#* }
	
	# Catch sigchilds, and abort. The user probably hit ctrl-c..
	# (Note that if we already trapped sigint above, then this has no
	# effect anyway.)
	trap cleanup 20
	set +e
	./$script $PARAM
	CODE=$?
	set -e
	# Untrap to prevent other child processes from killing base-config.
	trap 20

	if [ "$CODE" != 0 -a "$CODE" -lt 10 ] || [ "$CODE" -gt 100 ]; then
		echo "base-config: $script exited with return code $CODE" 2>&1
		# Don't really fail for now anyway. May change later.
	elif [ "$CODE" -ge 10 -a "$CODE" -le 100 ]; then
		echo jump to $CODE
		# Jump to CODE. Just reset SCRIPTS and scan forward until
		# we get to someting marked CODE or higher.
		SCRIPTS="$ORIGSCRIPTS"
		while [ ! -z "$SCRIPTS" ]; do
			if [ "$(expr "$SCRIPTS" : '\([0-9]*\)')" -ge "$CODE" ]; then
				break
			fi
			SCRIPTS=${SCRIPTS#* }
		done
	fi
done

cleanup
# That's all, folks! (On an initial install, the user sees a login prompt next)
