#!/usr/bin/env bash
# Copyright (c) 2022, 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.

# Script to run a benchmark compiled using dart2wasm. Assumes the Dart repo's
# directory structure.
#
# This is also used by the test runner.

set -e

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.
PROG_DIR="$(cd "${PROG_NAME%/*}" ; pwd -P)"
source "$PROG_DIR/utils.sh"

RUN_WASM="$SDK_DIR/pkg/dart2wasm/bin/run_wasm.js"


function host_os() {
  if [[ `uname` == 'Darwin' ]]; then
    echo 'macos'
  else
    echo 'linux'
  fi
}

D8_BIN="$SDK_DIR/third_party/d8/$(host_os)/$(get_host_arch)/d8"
JSSHELL_BIN="$SDK_DIR/third_party/firefox_jsshell/js"
JSC_BIN="$SDK_DIR/third_party/jsc/jsc"

SHELL_BIN="$D8_BIN"
SHELL_OPTIONS=()
SHELL_ARG_SEPERATOR="--"
MJS_FILE=""
WASM_FILE=""
LINEAR_WASM_FILES=()
EXTRA_JS_FILES=()
while [ $# -gt 0 ]; do
  case "$1" in
    --d8)
      SHELL_BIN="$D8_BIN"
      SHELL_ARG_SEPERATOR="--"
      shift
      ;;

    --jsshell)
      SHELL_BIN="$JSSHELL_BIN"
      SHELL_ARG_SEPERATOR=""
      shift
      ;;

    --jsc)
      SHELL_BIN="$JSC_BIN"
      SHELL_ARG_SEPERATOR="--"
      shift
      ;;

    --shell-option=*)
      SHELL_OPTIONS+=("${1#--shell-option=}")
      shift
      ;;

    *.js)
      EXTRA_JS_FILES+=("$1")
      shift
      ;;

    *.wasm)
      if [ -z "$WASM_FILE" ]; then
        # First wasm file is the actual dart program
        WASM_FILE="$(get_realpath "$1")"
        MJS_FILE="${WASM_FILE%.wasm}.mjs"
      else
        # Following wasm files are imported linear memory modules
        LINEAR_WASM_FILES+=("$1")
      fi
      shift
      ;;

    *)
      # Any arguments that are not the above will be arguments to the dart's
      # main function.
      break
      ;;
  esac
done

exec "$SHELL_BIN" "${SHELL_OPTIONS[@]}" "${EXTRA_JS_FILES[@]}" "$RUN_WASM" $SHELL_ARG_SEPERATOR "$MJS_FILE" "$WASM_FILE" "${LINEAR_WASM_FILES[@]}" -- "$@"
