#!/bin/sh -e
#
# 2003  Evgeny Sinelnikov Evgeny <sin@altlinux.ru>
#
# realtime kernel version selection utility.
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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.
#

PROG="${0##*/}"
VERSION="0.1"

REALTIME_DIR="/usr/lib/realtime"

fatal()
{
	echo "${0##*/}: $*" >&2
	exit 1
}

list_rtls()
{
	local list1="$(/bin/ls -d1 $REALTIME_DIR/*/bin/{rtai,xeno}-load 2>/dev/null |
		while read f; do
			find "$f" -maxdepth 1 2>/dev/null
		done |
		eval sed -e \'s,^$REALTIME_DIR/\\\([^/]\\+\\\)/bin/\(rtai\|xeno\)-load$,\\1,g\')"
	(echo "$list1") |
		sort -u |
		grep -v '^$'
}

usage()
{
	[ "$1" = 0 ] || exec >&2
	cat <<EOF
$PROG - select kernel version for RTAI and Xenomai

Usage: $PROG [OPTION | REALTIME-KERNEL-VERSION]

Valid options are:
  --auto            switch to automatic mode: use files for the running
                      realtime kernel if available, or nothing files otherwise;
  --list            show available versions of realtime kernels;
  --help            display this help and exit;
  --version         output version information and exit.

Available versions: $(list_rtls |xargs echo auto)
    
Report bugs to http://bugs.altlinux.ru/

EOF
	[ -n "$1" ] && exit "$1" || exit
}

try_adjust_realtime()
{
	local dir="$1"
	shift

	alternatives-manual /usr/realtime $dir && alternatives-update
	exit $?
}

case "$1" in
	help|--help|usage|--usage)
		usage 0
		;;
	--version)
		echo "$PROG: version $VERSION"
		exit 0
		;;
	list|--list)
		list_rtls
		exit 0
		;;
	''|auto|--auto)
		;;
	*)
		[ -n "${1##*/*}" ] &&
			[ "$1" = default -o -z "${1##[2-9].[0-9]*}" ] ||
			fatal "$1: invalid kernel version"
		try_adjust_realtime "$REALTIME_DIR/$1"
		fatal "$1: RTAI or Xenomai for this kernel version not installed"
		;;
esac

FULL_KERNEL_VERSION="$(uname -r)"
KERNEL_VERSION="$(echo "$FULL_KERNEL_VERSION" |sed -e 's/-alt[[:digit:]]\+\(\.[[:digit:]]\+\)\?//')"

try_adjust_realtime "$REALTIME_DIR/$KERNEL_VERSION"

exit 1
