1#!/bin/sh
2. /etc/functions.sh
3
4copy_kernel() {
5	local input="$1"
6	local output="$2"
7	local cmdline="$3"
8	size="$(echo -n "$cmdline" | wc -c)"
9	dd if="$input" bs=3M count=1 > "$output"
10	/sbin/patch-cmdline "$output" "$cmdline"
11}
12
13fstype="$(mount | grep ' / ' | awk '$5 != "rootfs" {print $5}')"
14case "$fstype" in
15	ext2|jffs2) echo "Copying from $fstype to yaffs2";;
16	*) echo "Invalid filesystem."; exit 1;;
17esac
18
19[ -d /tmp/cf2nand ] && {
20	echo "/tmp/cf2nand already exists"
21	exit 1
22}
23
24mkdir /tmp/cf2nand
25mkdir /tmp/cf2nand/rootfs
26mount -t "$fstype" /dev/root /tmp/cf2nand/rootfs || {
27	echo "Mounting rootfs failed."
28	exit 1
29}
30
31boot="$(find_mtd_part 'Routerboard NAND boot')"
32main="$(find_mtd_part 'rootfs')"
33[ -z "$boot" -o -z "$main" ] && {
34	echo "Cannot find NAND Flash partitions"
35	exit 1
36}
37
38echo "Erasing filesystem..."
39mtd erase Boot 2>/dev/null >/dev/null
40mtd erase Main 2>/dev/null >/dev/null
41
42mkdir /tmp/cf2nand/p1
43mkdir /tmp/cf2nand/p2
44mount -t yaffs2 "$boot" /tmp/cf2nand/p1
45mount -t yaffs2 "$main" /tmp/cf2nand/p2
46
47echo "Copying kernel..."
48copy_kernel /dev/cfa1 /tmp/cf2nand/p1/kernel "root=/dev/mtdblock1 rootfstype=yaffs2 " 2>/dev/null >/dev/null
49umount /tmp/cf2nand/p1
50rmdir /tmp/cf2nand/p1
51
52echo "Copying filesystem..."
53( cd /tmp/cf2nand/rootfs; tar c . ) | ( cd /tmp/cf2nand/p2; tar x )
54echo "chmod ugo+x /" > /tmp/cf2nand/p2/etc/uci-defaults/set_root_permission
55sync
56# Use kexec is present
57[ -x /usr/bin/kexec ] && {
58	kexec -l /tmp/cf2nand/p1/kernel --command-line="$(cat /proc/cmdline) root=/dev/mtdblock1 rootfstype=yaffs2"
59	kexec -e
60}
61umount /tmp/cf2nand/p2
62rmdir /tmp/cf2nand/p2
63
64umount /tmp/cf2nand/rootfs
65rmdir /tmp/cf2nand/rootfs
66rmdir /tmp/cf2nand
67
68