#!/bin/sh
# Script to run from a ramdisk, mounts compact flash (on SOURCE_DRIVE) and
# installs full Debian system from it to INSTALL_DRIVE. ADSBOARD should be
# set to the ads board name.

set -e

# Run as init.
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
export PATH

echo "Starting ADS Debian image installer..."

if [ -z "$ADSBOARD" ] || [ -z "$INSTALL_DRIVE" ]; then
	echo "Error: ADSBOARD, SOURCE_DRIVE, and INSTALL_DRIVE must be set to run this program"
	exit 1
fi

mount -o remount,rw /
mount /proc || true
/etc/init.d/pcmcia start
/etc/init.d/hotplug start
sleep 3 # wait for pcmcia and usb to settle

# Make sure the clock is set to avoid fsck on booting the installed system.
/etc/init.d/hwclockfirst.sh start

umount /mnt/ 2>/dev/null || true
while ! mount -t vfat $SOURCE_DRIVE /mnt && ! mount -t msdos $SOURCE_DRIVE /mnt; do
	echo "Error: Failed to mount $SOURCE_DRIVE. Make sure the compact flash card is inserted"
	printf "Press enter to retry."
	read fnord
done

for file in debian_install.sh initrd.gz debian-root.tar.gz; do
	if [ -e /mnt/debian-install/image/$file ]; then
		filedir=/mnt/debian-install/image/
		kerneldir=../../$ADSBOARD
		auto="-a"
	elif [ -e /mnt/$file ]; then
		filedir=/mnt
		kerneldir=/mnt
		auto=""
	else
		echo "Error: compact flash card does not contain $file. Cannot install."
		exit 1
	fi
done

cd $filedir
while ! bash ./debian_install.sh $auto debian-root.tar.gz initrd.gz $kerneldir/zImage $INSTALL_DRIVE; do
	echo "Error: Installation failed"
	echo "Dropping to shell"
	sh
done
cd /

umount /mnt

sync
sync
sync

echo "Installation complete. Reset board to continue."
read pause
reboot -f
