#!/bin/sh
# Copyright (C) 2006 OpenWrt.org
. /etc/functions.sh

clean() {
	echo -ne '\xde\xad\xc0\xde' > "$1"
}


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
		mount -o move $2/jffs /jffs 2>&-
		return 0
	}
}

mount_overlay() {
	root="$(find_part $1)"
	config="$(find_part config)"
	[ -z "$root" -o -z "$config" -o -z "$1" ] && return 0
	configstate="$(dd if=$config bs=2 count=1 2>/dev/null | hexdump -C | awk '/00000000/{print $2 $3}')"
	case "$configstate" in
		1337)
			# Should be usable...
			echo "JFFS OK"
		;;
		1f8b)
			echo "Restoring config..."
			gunzip -c < "$config" > /tmp/config.tar
			clean "$root"
		;;
		*) clean "$root";;
	esac
	mount -t jffs2 "$root" /jffs || {
		echo "JFFS2 unusable."
		# try again
		clean "$root"
		mount -t jffs2 "$root" /jffs || return 1
	}
	insmod mini_fo >&- 2>&-
	mount -t mini_fo -o base=/,sto=/jffs / /mnt
	pivot /mnt /rom && {
		cd /
		tar xvf /tmp/config.tar
		echo -ne '\x13\x37' > "$config"
	}
}

mount none /proc -t proc
size=$(awk '/Mem:/ {l=5242880;print((s=$2/2)<l)?$2-l:s}' /proc/meminfo)
mount none /tmp -t tmpfs -o size=$size,nosuid,nodev,mode=1777
mkdir -p /dev/pts
mount none /dev/pts -t devpts
mount -t sysfs none /sys 2>&-
if grep jffs2 /proc/mounts >/dev/null 2>/dev/null; then
	mount -o remount,rw /dev/root /
else
	mount_overlay rootfs1
fi

