#!/usr/bin/env bash
# Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.

function follow_links() {
  file="$1"
  while [ -h "$file" ]; do
    # On Mac OS, readlink -f doesn't work.
    file="$(readlink "$file")"
  done
  echo "$file"
}

# Unlike $0, $BASH_SOURCE points to the absolute path of this file.
PROG_NAME="$(follow_links "$BASH_SOURCE")"

# Handle the case where dart-sdk/bin has been symlinked to.
CUR_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)"

if [[ `uname` == 'Darwin' ]];
then
  OUT_DIR="$CUR_DIR"/../../xcodebuild/
else
  OUT_DIR="$CUR_DIR"/../../out/
fi

if [ -z "$DART_CONFIGURATION" ];
then
  DIRS=$( ls "$OUT_DIR" )
  # list of possible configurations in decreasing desirability
  CONFIGS=("ReleaseX64" "ReleaseARM64" "ReleaseIA32" "DebugX64" "DebugIA32"
    "ReleaseARM" "DebugARM" "DebugARM64" )
  DART_CONFIGURATION="None"
  for CONFIG in ${CONFIGS[*]}
  do
    for DIR in $DIRS;
    do
      if [ "$CONFIG" = "$DIR" ];
      then
        # choose most desirable configuration that is available and break
        DART_CONFIGURATION="$DIR"
        break 2
      fi
    done
  done
  if [ "$DART_CONFIGURATION" = "None" ]
  then
    echo "No valid dart configuration found in $OUT_DIR"
    exit 1
  fi
fi

BIN_DIR="$OUT_DIR$DART_CONFIGURATION"

exec "$BIN_DIR"/dart-sdk/bin/dart "$@"
