#!/bin/sh

# Params:
# $0: /tmpData/upd@te/updater
# $1: -v
# $2: /tmpData
# ls /tmpData: @autoupdate, upd@te, .noroot
# pwd: /usr/syno/web/webman

ROOTMNT="/tmpRoot"
#DATA="/tmpData" # Got from $2
DataMnt=$2
TmpMnt="/mnt"
RootDevice="/dev/md0"
# For 1-disk device we need get correct root path from kernel cmdline (/dev/sda1):
for item in `cat /proc/cmdline` ; do
	if [ "`echo $item | cut -d'=' -f 1`" = "root" ]; then
		RootDevice="`echo $item | cut -d'=' -f 2`"
		break
	fi
done

ROOTFS="${DataMnt}/upd@te/hda1.tgz"
KERNEL="${DataMnt}/upd@te/uImage"
INITRD="${DataMnt}/upd@te/uRamdisk"
CONFIG="${DataMnt}/upd@te/synoinfo.conf"

# Gol to file...
logtofile () {
	echo `date` $1 >> /var/log/messages
}

#####################################################
logtofile "# Updater started..."
logtofile "# Got params: ${1} ${2}"
logtofile "# Root device: ${RootDevice}"

if [ ! -d $ROOT ]; then
	logtofile "# Rootfs not mounted. Mount it..."
	mkdir $ROOT
	mount $RootDevice $ROOT
fi

if [ -e $ROOTFS ]; then
	logtofile "# Found hda1.tgz. Installing..."
	#tar xvf $ROOTFS -C $ROOT
	tar xvf $ROOTFS -C $2
fi

if [ -e $KERNEL ]; then
	logtofile "# Found uImage. Installing..."
	#dd if=$KERNEL of=/dev/mtdblock1
fi

if [ -e $INITRD ]; then
	logtofile "# Found uRamdisk. Installing..."
	#dd if=$INITRD of=/dev/mtdblock2
fi

if [ -e $CONFIG ]; then
	logtofile "# Found synoinfo. Installing..."
	# TODO: Use sed/awk for replace strings in this file.
	cp $CONFIG $ROOT/etc.defaults/
fi

if [ -f $ROOT/.noroot ]; then
	rm $ROOT/.noroot
fi

logtofile "# Cleanup..."
umount $ROOT 2 > /dev/null

logtofile "# Done."
