#!/bin/sh

# use Pacman to install the TeraGrid Client Toolkit - this gets a bit
# hairy since we do some processing on Pacman's output so that:
#   - we can display a primitive indicator of the install's progress
#   - we can tell if the install failed, even if Pacman returns a 0 for
#     its exit status (which it does if it gets SIGINT)

# pacman_wrapper
#
#   shell function for invoking pacman. it checks the exit status and touches
#   a file if its nonzero. this is needed since we run pacman at the start of
#   a pipeline, but we need to know whether it exits with success. this
#   function expects the PACMAN_GET_OPTION and PACMAN_PLATFORM_OPTION
#   variables to be set up by the caller
#
pacman_wrapper ( ) {
	if ! pacman -v all $PACMAN_GET_OPTION $PACMAN_PLATFORM_OPTION
	then
		touch pacman-failure-marker
	fi
}

# process_pacman_output
#
#  this is a shell function that is meant to be used in a pipeline after
#  Pacman. it expects Pacman output to show up on its stdin. it echos all
#  input to stdout and also outputs a progress indicator to /dev/tty
#
process_pacman_output ( ) {
	if ( : < /dev/tty ) > /dev/null 2>&1
	then
		TTY=/dev/tty
	else
		TTY=/dev/null
	fi
	_FAILURE=0
	echo "Searching for packages..." > $TTY
	echo -n "[" > $TTY
	while read _LINE
	do
		echo "$_LINE"
		if echo "$_LINE" | grep -q '^Package \[[^:]*\] found'
		then
			echo -n "*" > $TTY
		elif echo "$_LINE" | grep -q '^Installing package \[.*\]'
		then
			break
		elif echo "$_LINE" | grep -q '^\^C user interrupt'
		then
			_FAILURE=1
		fi
	done
	echo "]" > $TTY
	echo "Installing packages..." > $TTY
	echo -n "[" > $TTY
	while read _LINE
	do
		echo "$_LINE"
		if echo "$_LINE" | grep -q '^Installing package \[.*\]'
		then
			echo -n "*" > $TTY
		elif echo "$_LINE" | grep -q '^\^C user interrupt'
		then
			_FAILURE=1
		fi
	done
	echo "]" > $TTY
	return $_FAILURE
}

# determine the "-get" option to give to Pacman
#
DEFAULT_LOCATION=http://www.cs.wisc.edu/~gquinn/teragrid/pacman:TeraGrid-Client
if [ -z "$TERAGRID_CLIENT_PACKAGE_LOCATION" ]
then
	TERAGRID_CLIENT_PACKAGE_LOCATION=$DEFAULT_LOCATION
fi
PACMAN_GET_OPTION="-get $TERAGRID_CLIENT_PACKAGE_LOCATION"

# determine the "-pretend-platform" option (if any) to give to Pacman
#
if [ -n "$TERAGRID_CLIENT_PLATFORM" ]
then
	PACMAN_PLATFORM_OPTION="-pretend-platform $TERAGRID_CLIENT_PLATFORM"
fi

# invoke Pacman
#
pacman_wrapper 2>&1 | process_pacman_output
PROCESS_PACMAN_OUTPUT_STATUS=$?
if [ -f pacman-failure-marker ]
then
	rm pacman-failure-marker
	exit 1
fi
if [ "$PROCESS_PACMAN_OUTPUT_STATUS" -ne 0 ]
then
	exit 1
fi
