#!/bin/sh

set -e

FRONTEND=$1
PRIORITY=$2

cleanup () {
	# Stopping syslogd/klogd
	# ->the sed horror could be improved (FIXME;)
	# string: [A-Z][a-z]: [0-9] [0-9]rce [0-9]...
	# we only want the [0-9]rce, but without the rce.
	for PID in $(fuser -m /live/installer/var/log/syslog 2>&1 | \
		sed "s,.*: ,,g;s, ,\n,g" | grep 'rce$' | \
		sed -e 's/rce//g'); do
		kill -9 $PID > /dev/null 2>&1 || true
	done

	# Unmounting installer cdrom
	umount -f /live/installer/cdrom > /dev/null 2>&1 || true

	# Unmounting pseudo filesystems
	umount -f /live/installer/dev/pts > /dev/null 2>&1 || true
	umount -f /live/installer/dev > /dev/null 2>&1 || true
	umount -f /live/installer/proc > /dev/null 2>&1 || true
	umount -f /live/installer/sys > /dev/null 2>&1 || true
	umount -f /live/installer/tmp > /dev/null 2>&1 || true

	# Remove unpacked initrd
	rm -rf /live/installer
	rm -f /tmp/live-installer
}

# Setup cleanup function
trap 'cleanup' EXIT HUP INT QUIT TERM

if [ -z $FRONTEND ] || [ -z $PRIORITY ]; then
	/usr/share/live-installer-launcher/debconf.sh
fi

# Source configuration found by debconf
. /tmp/live-installer

# Find an debian-installer initrd, preferably the gtk one
for IMAGE in /live/image/install/gtk/initrd.gz /live/image/install/initrd.gz; do
	[ -e $IMAGE ] && break
done

[ ! -e $IMAGE ] && echo "no suitable d-i initrd image found, aborting." && exit 1

echo "Loading debian-installer..."

# Create the temporary directory
mkdir -p /live/installer

# Unpack the initrd
cd /live/installer
zcat $IMAGE | cpio -id > /dev/null 2>&1

# Bindmount pseudo filesytem
mount -o bind /dev /live/installer/dev
mount -o bind /dev/pts /live/installer/dev/pts
mount -o bind /proc /live/installer/proc
mount -o bind /sys /live/installer/sys
mount -o bind /tmp /live/installer/tmp

# Preseeding shutdown command
cat >> preseed.cfg << EOF
# Select udeb for installation to allow exiting the installer
d-i anna/choose_modules string di-utils-exit-installer
# Ask question regardless from that it's preseeded above
d-i anna/choose_modules seen false
EOF

# Preseeding installer export mode
if [ "$PRIORITY" = expert ]
then

cat >> preseed.cfg << EOF
# Setting expert mode
d-i debconf/priority select low
debconf debconf/priority select low
EOF

fi

# Configuring directfb
cat > etc/directfb << EOF
system=x11
force-windowed
EOF

# Launching debian-installer
/usr/share/live-installer-launcher/debian-installer.sh
