#!/bin/sh -e

WITH_ACTION=1
. install2-init-functions

charset=utf8
cmdline="$(cat /proc/cmdline)"

init_splash()
{
	splash_nbservices=
	for d in $cmdline; do
		[ -z "${d%%splashcount=*}" ] || continue
		splash_nbservices="${d#splashcount=}"
		break
	done
	export splash_nbservices
}

update_splash()
{
	[ -x /sbin/splash.sh ] || return 0
	splash_progress=$(($splash_nbservices-$1)) /sbin/splash.sh ||:
}

mount_fs()
{
	mount-unionfs /var
	mount-unionfs /etc
}

set_alterator_datadir()
{
	ALTERATOR_DATADIR="/usr/share/alterator:$destdir/usr/share/alterator:$datadir"
	export ALTERATOR_DATADIR
}

set_duringinstall()
{
	DURING_INSTALL=1
	export DURING_INSTALL
}

set_locale()
{
	LANG=
	export LANG

	local lang=
	for d in $cmdline; do
		[ -z "${d%%lang=*}" ] || continue
		lang="${d#lang=}"
		break
	done
	[ -n "$lang" ] || return 0
	locale -a |cut -d. -f1 |fgrep -xqs "$lang" || return 0

	LANG="$lang.$charset"
}

set_autoinstall()
{
	AUTOINSTALL=
	export AUTOINSTALL

	if egrep -qs '(^|[[:space:]])ai([[:space:]]|$)' /proc/cmdline; then
		AUTOINSTALL='/tmp/metadata/autoinstall.scm'
	fi
}

set_cdromdev()
{
	CDROMDEV=
	export CDROMDEV

	[ "$METHOD" = cdrom ] || return 0
	CDROMDEV="$(sed -n 's,^\(/dev/[^[:space:]]\+\) '"$image_dir"' .*,\1,p' /proc/mounts)"
	[ -b "$CDROMDEV" ] ||
		fatal "cannot find cdrom device file $CDROMDEV for $image_dir"
}

if_run_debug_shell()
{
	egrep -iqs '(^|[[:space:]])instdebug([[:space:]]|$)' /proc/cmdline || return 0
	echo 'Executing shell for debug purposes'
	HOME=/root bash -l
}

# Mount
action 'Mounting filesystems' mount_fs
init_splash
update_splash 6

# Define HOME and TMPDIR into writable place
export HOME=/tmp
export TMPDIR=/tmp
export INSTALLER=1

service udevd start
update_splash 5

set_alterator_datadir
set_locale
update_splash 4

set_autoinstall
update_splash 3

set_duringinstall
update_splash 2

set_cdromdev
update_splash 1

initinstall
update_splash 0

if_run_debug_shell
rc=0

PATH=/usr/lib/alterator-x11:$PATH
XORG_CONF='/etc/X11/xorg.conf'

if [ -s "$AUTOINSTALL" ]; then
	echo 'Starting autoinstaller...'
	alterator-autoinstall "$AUTOINSTALL" && text=done || text=FAILED
	echo "autoinstall $text"
else
	echo 'Starting Xorg server...'

	auto_drivers="$(video_scan -s drivers)"

	xinit_args='vt7 -dpms -ac -dpi 80 -nolisten tcp -logfile /tmp/x11.log'
	eval $(grep -s ^xinit_args= /etc/xserver-args) ||:
	cmd="xinit /usr/sbin/alterator-install2 -- $xinit_args"

	if ! $cmd >>/tmp/install2.log 2>&1; then
		for drv in $auto_drivers; do
			echo "Error running Xorg server, trying with driver $drv..."
			video_setup "$drv" "$XORG_CONF"
			$cmd >>/tmp/install2.log 2>&1 && break || rc=$?
		done
	fi
fi

if_run_debug_shell
[ "$rc" -ne 0 ] || postinstall
exit $rc
