#!/bin/sh
#
# build 2.9 - Compile the kernel and install the result
#							Author: Kees J. Bot
#

ver_file=../version/version.h
rev_file=../version/revision.c
timestamp=../version/timestamp

newname()
{
	#
	# Get the O.S. release, version and revision.
	#

	release=`sed '/OS_RELEASE/!d; s/.*"\(.*\)".*/\1/' < $ver_file`
	version=`sed '/OS_VERSION/!d; s/.*"\(.*\)".*/\1/' < $ver_file`
	revision=`sed 's/[^0-9]*\([0-9]*\)[^0-9]*/\1/' < $rev_file`

	case $release:$version:$revision in
	:*:*|*::*|*:*:)		exit 1
	esac

	#
	# Name of the new image.
	#

	image=${release}.${version}r${revision}
}

case $#:$1 in
0)	;;
1:-newrev)
	# Called from the task Makefiles to increase the revision numbers.

	if [ ! -f $rev_file ]
	then
		# Clean compile, no revision file yet.
		revision=0
	elif [ $rev_file -newer $timestamp ]
	then
		# Revision is already updated in this build.
		exit
	else
		# Increment the current revision by one.
		revision=`sed 's/[^0-9]*\([0-9]*\)[^0-9]*/\1/' < $rev_file`
		case $revision in
		'')	exit 1
		esac
		revision=`expr $revision + 1`
	fi

	echo "int revision= $revision;" > $rev_file
	echo "Revision set to $revision"
	exit
	;;
1:-name)
	# Called from the image Makefile to tell the new image name.
	newname
	echo "$image"
	exit
	;;
*)	# Extra CFLAGS options, usually -O.
	OPT="$*"
	export OPT
esac

#
# The kernel sources may be found in a subdirectory of the source directory.
# I.e. /usr/src/*/{kernel,mm,fs,...}
#

cwd=`pwd`
if expr $cwd/ : '/usr/src/[^/]*/' >/dev/null
then
	target=`expr $cwd/ : '/usr/src/\([^/]*\)/'`
	: "${target:=sys}"
else
	echo "build: You must be in one of the kernel directories" >&2
	exit 1
fi

#
# Enter the proper kernel images directory.  Use a build tree if possible.
#

build=/usr/build
test -d /usr/build || build=/usr/src
build=$build/$target

if cd $build/tools
then
	echo "Building a Minix image in $build."
else
	echo "$target doesn't seem to contain a Minix kernel." >&2
	exit 1
fi

#
# Try to make the image.
#

echo "cd tools; make"
make || exit

#
# Name of the new image.
#
newname

#
# Delete old images.
#
find . -mtime +7 -name '*.*' -perm -200 ! -name $image | xargs rm

#
# Install new image
#
test /minix/$image -newer $image && exit	# Already there.

set -- `ls -t /minix`

case $# in
0|1)
	# Not much there, do not remove a thing.
	;;
*)
	# Remove the newest image in /minix.  This seems strange, but the old
	# image is normally the "stable" image.

	echo "rm /minix/$1"
	rm -f "/minix/$1"
esac

#
# Put a new image in place.
#

echo cp $image /minix/$image
cp -p $image /minix/$image || exit

# Let the next build increase the revision number.
test $rev_file -newer $timestamp && > $timestamp

echo Done.
