# BerryBoot, ugly but functional image chooser thingy
# Author: Floris Bos

# Standard busybox init
/bin/mount -t proc proc /proc
/bin/mount -o remount,rw,noatime / 
/bin/mount -a
/bin/hostname -F /etc/hostname

# Enumerate images
cd /images
IMAGES=`echo *`
DIALOG_ARGS="--backtitle 'BerryBoot v0.1' --menu 'Select operating system to boot:' 15 50 10"

for image in $IMAGES
        DIALOG_ARGS="$DIALOG_ARGS '$image' ''"

# Prevent kernel messages being printed through our menu
echo 0 > /proc/sys/kernel/printk

# Show dialog
eval dialog $DIALOG_ARGS 2>/tmp/answer

if [ $? -eq 0 ]; then
        echo 1 > /proc/sys/kernel/printk
        IMAGE=`cat /tmp/answer`
        rm /tmp/answer
        mkdir -p /mnt/squashfs /mnt/aufs $DATADIR
        modprobe aufs
        modprobe squashfs
        echo Mounting image ${IMAGE}...
        mount -o loop $IMAGE /mnt/squashfs
        echo Mounting RW data directory on top
        mount -t aufs -o br:${DATADIR}:/shared:/mnt/squashfs none /mnt/aufs
        cd /mnt/aufs
        mkdir -p -m 700 .berryboot
        umount /sys
        umount /dev/pts
        umount /dev/shm
        umount /tmp
        umount /proc
        pivot_root . .berryboot 
        exec chroot . /sbin/init </dev/console 2>/dev/console

# In case the user pressed cancel or something went wrong, show an emergency recovery shell
echo Emergency shell activated
echo To get network connectivity: udhcpc eth0 - wget can be used to download things
echo Squashfs images are in /images
echo User changes to the images are in /data
echo Before shutting down remount readonly: mount -o remount,ro /