#!/bin/bash

# Determine the path to this script (we'll use this to figure out relative positions of other files)
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  SCRIPT_PATH="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
export SCRIPT_PATH="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"

# Check if we are running 'Dev Mode' and if so, override values for devs
QUARTO_SRC_DIR="`cd "$SCRIPT_PATH/../../../src" > /dev/null 2>&1 && pwd`"
DEV_PATH=$QUARTO_SRC_DIR/quarto.ts
if [ -f "$DEV_PATH" ]; then

  # Caller can point deno at another entry point (e.g. the typescript file)
  if [ -z ${QUARTO_ACTION+x} ]; then
    QUARTO_ACTION=run
  fi

  # Local import map
  QUARTO_IMPORT_ARGMAP=--importmap=$QUARTO_SRC_DIR/import_map.json

  # Allow calls to override the target
  if [ -z ${QUARTO_TARGET+x} ]; then
    QUARTO_TARGET=$DEV_PATH
  fi
  export QUARTO_BIN_PATH=$SCRIPT_PATH
  export QUARTO_SHARE_PATH="`cd "$SCRIPT_PATH/../../../src/resources/";pwd`"
  export QUARTO_DEBUG=true

  if [ "$1" == "--version" ]; then
    echo "99.9.9"
    exit 0
  fi

else 
  
  QUARTO_ACTION=run
  QUARTO_TARGET=${SCRIPT_PATH}/quarto.js
  export QUARTO_BIN_PATH=$SCRIPT_PATH
  export QUARTO_SHARE_PATH="`cd "$SCRIPT_PATH/../share";pwd`"

  if [ "$1" == "--version" ]; then
    echo `cat "$QUARTO_SHARE_PATH/version"`
    exit 0
  fi

fi

if [ "$1" == "--paths" ]; then
  echo "$QUARTO_BIN_PATH"
  echo "$QUARTO_SHARE_PATH"
  exit 0
fi


QUARTO_DENO_EXTRA_OPTIONS=""
QUARTO_DENO_OPTIONS="--unstable --allow-read --allow-write --allow-run --allow-env --allow-net"

${SCRIPT_PATH}/deno ${QUARTO_ACTION} ${QUARTO_DENO_OPTIONS} ${QUARTO_DENO_EXTRA_OPTIONS} ${QUARTO_IMPORT_ARGMAP} ${QUARTO_TARGET} "$@"