#!/bin/bash
#@DOC@ save kernel in archive dir
#
# Copyright (C) 2006  Nathan (Acorn) Pooley
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
# 
# 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 (gpl.txt) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
# 
# You can contact the author, Nathan (Acorn) Pooley, by writing
# to Nathan (Acorn) Pooley, 949 Buckeye Drive, Sunnyvale, CA  94086, USA
# or through the form at http://www.rawbw.com/~acorn/wand/feedback.html
# 

mkdir -p Archive

_err() {
	echo "savekern: ERROR: $*"
	exit 1
}

ver=`grep '#define.*KK_VERSION' kernel.inc |
	sed -n \
		-e 's|[^!-~]| |g' \
		-e 's|[ 	][ 	]*| |g' \
		-e 's|^ *#define KK_VERSION \([0-9][0-9a-fA-Fx]*\) *$|\1|p'`

echo "ver=$ver"

(( version = ver + 0 ))
if (( version < 1 )) ; then
	_err "Bad kernel version: $version"
fi
if (( version > 255 )) ; then
	_err "Bad kernel version: $version"
fi

if [[ ! -s kernel.inc ]] ; then
	_err "Could not find kernel.inc"
fi

isok=1
rm -f kload.hex
make kload.hex || isok=0

if (( ! isok )) ; then
	_err "Could not build kload.hex"
fi

if [[ ! -s kload.hex ]] ; then
	_err "Could not find kload.hex"
fi

rev=""
while (( 1 )) 
do
	kdst="Archive/kernel.v$version$rev.inc"
	kldst="Archive/kload.v$version$rev.hex"
	if [[ ! -a $kdst && ! -a $kldst ]] ; then
		break
	fi
	case x$rev in
		x)	rev=a	;;
		xa)	rev=b	;;
		xb)	rev=c	;;
		xc)	rev=d	;;
		xd)	rev=e	;;
		xe)	rev=f	;;
		xf)	rev=g	;;
		xg)	rev=h	;;
		xh)	rev=i	;;
		xi)	rev=j	;;
		xj)	rev=k	;;
		xk)	rev=l	;;
		*)	rev=xxx	;;
	esac
	if [[ x$rev != x[a-z] ]] ; then
		_err "Could not find unused filename in Archive directory"
	fi
done

echo "Saving kernel.inc as $kdst"
echo "Saving kload.hex  as $kldst"

cp -v kernel.inc "$kdst"
cp -v kload.hex  "$kldst"
