#!/bin/bash

export FROM_CHARMRUN='1'

pre_args=()
cmd=""
args=()
QUIET=0
XTERM='xterm'
DEBUG=0
DEBUG_NO_PAUSE=0
DEBUGGER=''

runCmd()
{
  [[ $QUIET -eq 0 ]] && echo "charmrun>" "$@"
  "$@"
}

while [[ $# -ne 0 ]]
do
	case "$1" in
	+p|++p|+ppn|++ppn)
		args+=("$1" "$2")
		shift
		shift
		;;
	+n|++n|++np)
		if [[ "$2" != 0 && "$2" != 1 ]]
		then
			printf "Charmrun> Error: Multicore builds only support single-node runs.\n"
		 	exit 1
		fi
		shift
		shift
		;;
	+n0|+n1)
		shift
		;;
	+n[0-9]*)
		printf "Charmrun> Error: Multicore builds only support single-node runs.\n"
		exit 1
		shift
		;;
	++quiet)
		QUIET=1
		shift
		;;
	++no-quiet)
		QUIET=0
		shift
		;;
	++local|++no-local)
		# consume and ignore, local-mode is all that multicore supports
		shift
		;;
	++xterm)
		XTERM="$2"
		shift
		shift
		;;
	++debug)
		DEBUG=1
		shift
		;;
	++no-debug)
		DEBUG=0
		shift
		;;
	++debug-no-pause)
		DEBUG_NO_PAUSE=1
		shift
		;;
	++no-debug-no-pause)
		DEBUG_NO_PAUSE=0
		shift
		;;
	++debugger)
		DEBUGGER="$2"
		shift
		shift
		;;
	+*)
		args+=("$1")
		shift
		;;
	*)
		if [[ -z "$cmd" ]]; then
			cmd="$1"
		else
			args+=("$1")
		fi
		shift
		;;
	esac
done

[[ $QUIET -eq 1 ]] && args+=(++quiet)

if [[ "$DEBUG" = '1' || "$DEBUG_NO_PAUSE" = '1' ]]
then
  if [[ -z "$DEBUGGER" ]]
  then
    [[ "$(uname -s 2>/dev/null)" = 'Darwin' ]] && DEBUGGER='lldb' || DEBUGGER='gdb'
  fi

  DEBUG_RUN=(-ex r)
  DEBUG_POSTFIX='--args'
  if [[ "$DEBUGGER" = 'lldb' ]]
  then
    DEBUG_RUN=(-o r)
    DEBUG_POSTFIX='--'
  fi

  pre_args=("$DEBUG_POSTFIX" "${pre_args[@]}")
  [[ "$DEBUG_NO_PAUSE" = '1' ]] && pre_args=("${DEBUG_RUN[@]}" "${pre_args[@]}")
  pre_args=("$XTERM" -e "$DEBUGGER" "${pre_args[@]}")
fi

runCmd "${pre_args[@]}" "$cmd" "${args[@]}"
