#! /bin/bash
#
#	mangaflash - Copy binary images to/from onboard flash partitions
#		(c) 2005, Alexander R Perry <alex.perry@ieee.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; specifically version 2 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation Inc, 59 Temple Place, Suite 330, Boston,MA 02111-1307 USA
#
#    Debian systems have the text in /usr/share/common-licenses/GPL-2


if [ $# -ne 3 ]
then	echo "Usage:"
	echo "     $0 operation partition binaryfile"
	echo "where   operation  = read, write, verify"
	echo "        partition  = kernel, initrd, user"
	echo "        binaryfile = zImage, fsgz, whatever"
	exit 1
fi

SZ=65536
case $2 in
	kernel)  BEG=1;  LEN=8;;
	initrd)  BEG=9;  LEN=54;;
	user)    BEG=63; LEN=1;;
	*)       exec $0; exit 1;;
esac

if [ z$1 == zread ]
then	
	if [ -e $3 ]
	then	echo $3 already exists.
		exit 1
	fi
else
	if ! [ -f $3 ]
	then	echo $3 is not an ordinary file.
		exec $0
		exit 1
	fi
	actual=`wc -c < $3`
	if [ $actual -eq 0 ]
	then	echo $3 has zero length.
		exit 1
	fi
	if [ $actual -gt $(($SZ*$LEN)) ]
	then	echo $3 is too large ... max $((SZ*$LEN))
		exit 1
	fi

fi

F="/dev/ksflash bs=$SZ count=$LEN"

case $1 in
	read)   dd if=$F of=$3 skip=$BEG
	;;
	verify) dd if=$F       skip=$BEG |
		head -qc $actual |
		diff -qs - $3
	;;
	write)  dd if=$3 of=$F seek=$BEG
	;;
	*)      exec $0; exit 1;;
esac
