#!/bin/sh
#
# $Id$
# Copyright (C) 2000-2006  Dmitry V. Levin <ldv@altlinux.org>
# Copyright (C) 2003-2004  Stanislav Ievlev <inger@altlinux.org>
#
# GNU Compiler Collection (GCC) 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##*/}"

: ${TARGET:=armh-alt-linux-gnueabi}
: ${BINDIR:=/usr/bin}
: ${COMPILERS:='cpp gcc g++ gcj gfortran gtreelang chill'}
: ${ALT_LIST:='alternatives-list'}
: ${ALT_AUTO:='alternatives-auto'}
: ${ALT_MANUAL:='alternatives-manual'}
: ${ALT_UPDATE:='alternatives-update'}

info()
{
	printf %s\\n "$PROG: $*" >&2
}

fatal()
{
	printf %s\\n "$PROG: $*" >&2
	exit 1
}

show_usage()
{
	[ -z "$*" ] || info "$*"
	echo "Try \`$PROG --help' for more information." >&2
	exit 1
}

get_candidates()
{
	cat /etc/alternatives/packages.d/* |
    		grep "^$1"|
		cut -f2
}

show_help()
{
	local args='display|auto'
	local n
	for n in `get_candidates "$BINDIR/$TARGET-gcc" |sed -ne "s,$BINDIR/$TARGET-gcc-\\(.*\)$,\\1,pg" |sort -u`; do
		args="$args|$n"
	done

	cat <<EOF
$PROG - select GNU Compiler Collection.

Usage: $PROG {$args}
    
Report bugs to http://bugs.altlinux.ru/

EOF
	exit
}

# At least one argument, please.
[ "$#" -ge 1 ] ||
	show_usage 'Not enough arguments.'

case "$1" in
	help|usage|--help|--usage)
		show_help
		;;
	display)
		for n in $COMPILERS; do
			if [ -f "$BINDIR/$TARGET-$n" ]; then
				$ALT_LIST "$BINDIR/$TARGET-$n"
			fi
		done
		;;
	auto)
		for n in $COMPILERS; do
			if [ -f "$BINDIR/$TARGET-$n" ]; then
				$ALT_AUTO "$BINDIR/$TARGET-$n" >/dev/null 2>&1
			fi
		done
		$ALT_UPDATE
		;;
	*)
		[ -f "$BINDIR/$TARGET-gcc-$1" ] ||
			show_usage "$1: Unrecognized argument."

		for n in $COMPILERS; do
			if [ -f "$BINDIR/$TARGET-$n" -a -f "$BINDIR/$TARGET-$n-$1" ]; then
				$ALT_MANUAL "$BINDIR/$TARGET-$n" "$BINDIR/$TARGET-$n-$1" >/dev/null
			fi
		done
		$ALT_UPDATE
		;;
esac
