#!/bin/sh
is_dirty() {
        grep Broadcom /proc/cpuinfo >&- || return 1
        OFFSET="$(($(hexdump -v /dev/mtdblock/1 -s 20 -n 2 -e '"%d"')-1))"
        return $(hexdump -v /dev/mtdblock/1 -s $OFFSET -n 1 -e '"%d"')
}

pivot() { # <new_root> <old_root>
        mount -o move /proc $1/proc && \
        pivot_root $1 $1$2 && {
                mount -o move $2/dev /dev
                mount -o move $2/tmp /tmp
                return 0
        }
}

dupe() { # <new_root> <old_root>
        cd $1
        echo -n "creating directories... "
        {
                cd $2 
                find . -xdev -type d
                echo "./dev ./jffs ./mnt ./proc ./tmp"
                # xdev skips mounted directories
                cd $1 
        } | xargs mkdir -p
        echo "done"

        echo -n "setting up symlinks... "
        for file in $(cd $2; find . -xdev -type f;); do
                case "$file" in
                ./rom/note) ;; #nothing
                ./etc/resolv.conf|\
                ./usr/lib/ipkg/info) cp -af $2/$file $file;;
                *) ln -sf /rom/${file#./*} $file;;
                esac
        done
        for file in $(cd $2; find . -xdev -type l;); do
                cp -af $2/${file#./*} $file
        done
        echo "done"
}

mountdp() { # <device> <mount_point> <ignored> <fs>
        dev=$1; mnt=$2; shift 2; opt=$*
        mount $dev $mnt $opt
        dupe $mnt $rom
        pivot $mnt /rom
}

size=$(awk '/Mem:/ {l=5242880;print((s=$2/2)<l)?$2-l:s}' /proc/meminfo)
mount none /tmp -t tmpfs -o size=$size

mtd unlock linux
is_dirty
[ $? != 0 ] && {
	echo "switching to overlay filesystem"
	datanr=$(awk -F : '/data/ { print $1 }' /proc/mtd |sed "s#mtd##")
	mount /dev/mtdblock/$datanr /jffs -t jffs2
	mount -t mini_fo -o base=/,sto=/jffs /jffs /mnt
	pivot /mnt /rom
} || {
	echo "jffs2 unusable; using ramdisk"
	mkdir -p /tmp/root
	mountdp /tmp/root /mnt -o bind
}

mount none /tmp -t tmpfs -o remount,nosuid,nodev,mode=1777
mkdir -p /dev/pts
mount none /dev/pts -t devpts
