#!/usr/bin/env bash

set -eo pipefail

script_dir="$(dirname "$0")"

args=("$@")

# If the command is used like `yarn build plugin`, set the --build option to point to
# plugin/tsconfig.json
extra_module_build_types=("plugin" "cli" "utils" "scripts")
for i in "${extra_module_build_types[@]}"
do
  if [ "$1" == "$i" ]; then
    # Check if tsconfig.json exists in the directory
    if [ -f "$(pwd)/$i/tsconfig.json" ]; then
      # `--build` must be the first argument, so reset the array
      args=()
      args+=("--build")
      args+=("$(pwd)/$i")
      # Push the rest of the arguments minus the `plugin` arg
      args+=("${@:2}")
    else
      echo "tsconfig.json not found in $@, skipping build for $@/"
      exit
    fi
  fi
done

if [[ -t 1 && (-z "$CI" && -z "$EXPO_NONINTERACTIVE") ]]; then
  args+=("--watch")
fi

"$script_dir/expo-module-tsc" "${args[@]}"
