#!/usr/bin/env bash
# yarn-setup — install node_modules for MetaMask Mobile.
#
# Inputs:  --target <metamask-mobile dir>  (default $PWD)
#          --mode full|expo                 (default full)
# Outputs: yarn install output on stderr; exit 0 pass, 1 install failed, 2 bad args.
#
# Single device op: install node_modules. No other sequencing.
#   full — `yarn setup` (JS deps + expo prebuild + native pods/jetify). Use only
#          when a native build is wanted (launch --build / rebuild-native).
#   expo — `yarn setup:expo --no-build-ios --no-build-android` (JS deps + prebuild,
#          no native). The Metro-only remedy: native builds come from open-device.
set -euo pipefail

# Resolve SCRIPT_DIR before any cd (the script may be invoked by a relative path).
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

TARGET="$PWD"
MODE="full"
while [ "$#" -gt 0 ]; do
  case "$1" in
    --target)  TARGET="$2"; shift 2 ;;
    --mode)    MODE="$2"; shift 2 ;;
    -h|--help) printf 'Usage: yarn-setup.sh [--target <dir>] [--mode full|expo]\n'; exit 0 ;;
    *) printf 'yarn-setup: unknown arg: %s\n' "$1" >&2; exit 2 ;;
  esac
done

TARGET="$(cd "$TARGET" && pwd)"
cd "$TARGET"

# full mode runs native pods/jetify → pin the repo's Ruby so a cold checkout does
# not build iOS gems against the system Ruby. Best-effort (never blocks the setup).
# shellcheck disable=SC1091
for _rb in "$SCRIPT_DIR/../shared/activate-repo-ruby.sh" "$SCRIPT_DIR/lib/activate-repo-ruby.sh"; do
  [ -f "$_rb" ] && { . "$_rb"; break; }
done
unset _rb

case "$MODE" in
  full)
    command -v activate_repo_ruby_best_effort >/dev/null 2>&1 && activate_repo_ruby_best_effort "$TARGET"
    exec yarn setup ;;
  expo) exec yarn setup:expo --no-build-ios --no-build-android ;;
  *) printf 'yarn-setup: unknown --mode: %s (want full|expo)\n' "$MODE" >&2; exit 2 ;;
esac
