#!/bin/sh
# wget2nand
# This script can be used to download a TGZ file from your build system which
# contains the files to be installed on the NAND flash on your RB1xx card.
# The one parameter is the URL of the TGZ file to be downloaded.
# Licence GPL V2
# Author david.goodenough@linkchoose.co.uk
# Based on cf2nand from RB532 support
. /lib/functions.sh

wget2nand_dir=/tmp/wget2nand
mnt_kernel=$wget2nand_dir/mnt_kernel
mnt_rootfs=$wget2nand_dir/mnt_rootfs
src_rootfs=$wget2nand_dir/rootfs.tgz
src_kernel=$wget2nand_dir/kernel

[ -d "$wget2nand_dir" ] && {
	echo "$wget2nand_dir already exists"
	exit 1
}

# need to find the wget server from the command line
url=$1
[ -z "$url" ] && {
        echo "No URL specified for image TGZ"
        echo "Usage : $0 URL"
        exit 1
}

url_kernel=$url/librecmc-ar71xx-mikrotik-vmlinux-lzma.elf
url_rootfs=$url/librecmc-ar71xx-mikrotik-rootfs.tar.gz

mtd_kernel="$(find_mtd_part 'kernel')"
mtd_rootfs="$(find_mtd_part 'rootfs')"
[ -z "$mtd_kernel" -o -z "$mtd_rootfs" ] && {
	echo "Cannot find NAND Flash partitions"
	exit 1
}

mkdir "$wget2nand_dir"
wget $url_kernel -O "$src_kernel" || {
	echo "Unable to download $url_kernel"
	exit 1
}

wget $url_rootfs -O "$src_rootfs" || {
	echo "Unable to download $url_rootfs"
	exit 1
}

echo "Erasing filesystem..."
mtd erase kernel 2>/dev/null >/dev/null
mtd erase rootfs 2>/dev/null >/dev/null

echo "Mounting $mtd_rootfs as new root and $mtd_kernel as kernel partition"

mkdir "$mnt_kernel"
mkdir "$mnt_rootfs"
mount -t yaffs2 "$mtd_kernel" "$mnt_kernel"
mount -t yaffs2 "$mtd_rootfs" "$mnt_rootfs"

echo "Copying kernel..."
cp $src_kernel $mnt_kernel/kernel || {
       echo "Error occured while copying the kernel"
       exit 1
}
chmod +x $mnt_kernel/kernel

echo "Preparing filesystem..."
( cd "$mnt_rootfs"; tar xvz -f "$src_rootfs" )

# make sure everything is written before we unmount the partitions
echo "chmod ugo+x /" > $mnt_rootfs/etc/uci-defaults/set_root_permission
sync
ls $mnt_kernel >/dev/null
ls $mnt_rootfs >/dev/null

echo "Cleaning up..."
# unmount the partitions and remove the directories into which they were mounted
umount $mnt_kernel
umount $mnt_rootfs
rm -rf $wget2nand_dir

# all done
echo "Image written, you can now reboot.  Remember to change the boot source to Boot from Nand"
