#!/bin/bash
#This script runs a command and checks the output status. If the command fails,
#it waits for the user to press enter if running on a terminal or opens a
#terminal with the output from the command if not.
#
#The -E option exports an environment variable (in var=value format) to the
#guest; this is useful when used with terminal emulators where invoking them
#from the command line may send an RPC to an existing process to open a new
#terminal, which loses the environment from the original command
#
#The -e option saves the exit status to the specified file
#
#The -l option acquires the lock on the specified lock file
. "`dirname $0`/bootscriptfunctions.sh"

while [ x"$1" != x ]
do
	case "$1" in
		-E)
			shift
			export "$1"
			shift
			;;
		-e)
			shift
			EXIT_STATUS_FILE="$1"
			shift
			;;
		-l)
			shift
			lock_name_arg="$1"
			shift
			;;
		*)
			break
			;;
	esac
done

if [ ! "$1" ]
then
	echo "no command specified"
fi

if [ x"$lock_name_arg" != x ]
then
	acquire_global_lock -x -n "pause_on_fail: acquiring lock $lock_name_arg failed" "$lock_name_arg"
fi

if [ ! -t 1 ]
then
	output_file=`mktemp /tmp/osm_out.XXXXXXX`
	trap "rm -f $output_file ${output_file}.err" HUP INT TERM EXIT
	exec > "$output_file" 2>&1
fi

"$@"
status=$?
if [ -f "$EXIT_STATUS_FILE" ]
then
	echo $status > "$EXIT_STATUS_FILE"
fi
if [ $status != 0 ]
then
	if [ ! -t 1 ]
	then
		echo "Command failed" >> "${output_file}.err"
		echo "Output log:" >> "${output_file}.err"
		cat "$output_file" >> "${output_file}.err"
		x-terminal-emulator -e less "${output_file}.err"
	else
		echo "Command failed. Press enter to close this window."
		read
		exit $status
	fi
fi
