#!/usr/bin/env sh

set -e

self="rad"
module="./build/dev/javascript/${self}/${self}.mjs"

fail() {
  message="${1}"
  echo "\033[91m${message}\033[0m" 1>&2
  exit 1
}

config="gleam.toml"
if ! test -f "./${config}"; then
  fail "error: \`${config}\` not found; \`${self}\` must be invoked from a Gleam project's base directory"
fi

# Detect JavaScript runtime
runtime="node"
if grep -q '^\s*runtime\s*=\s*"deno"' "./${config}"; then
  runtime="deno"
fi

snag=""
for dependency in "gleam" "${runtime}"; do
  if ! type "${dependency}" > /dev/null 2>&1; then
    if test -n "${snag}"; then
      snag="${snag}\n"
    fi
    snag="${snag}error: \`${dependency}\` required but not found"
  fi
done
if test -n "${snag}"; then
  fail "${snag}"
fi

# Compile if necessary.
#
# Redirect stdout to stderr, keeping stdout clear for the given task.
#
if ! test -f "${module}"; then
  gleam build --target=javascript 1>&2
fi
if ! test -f "${module}"; then
  fail "error: \`${module}\` not found; try \`gleam add --dev ${self}\`"
fi

script="import('${module}').then(module => module.main())"
if test "${runtime}" = "deno"; then
  exec deno \
    eval "${script}" \
    --unstable \
    -- "${@}"
else
  exec node \
    --experimental-fetch \
    --experimental-repl-await \
    --no-warnings \
    --title="${self}" \
    --eval="${script}" \
    -- "${@}"
fi
