#!/bin/sh
# Stands in for `node` inside the crawler's container when a run is observed
# (gcli crawler test --observe). gcli puts the folder this is copied to,
# /tmp/_observatory/bin, first on PATH, so `npm start` finds it before the
# image's own node, whatever the sdk image is.
#
# Only the crawler's own script gets the probe: the first .js file on the
# command line that is not inside node_modules (lib/index.js, ./main.js...).
# npm, npx and tsc run from node_modules and go straight to the real node,
# as does everything when the run is not observed (OBSERVE unset).
PROBE=${OBSERVE_PROBE:-/tmp/_observatory/probe.js}
HERE=$(dirname "$0")

# the real node: the first one on PATH that is not this folder
REAL_NODE=
IFS=:
for dir in $PATH; do
    [ "$dir" = "$HERE" ] && continue
    [ "$dir" = /tmp/_observatory/bin ] && continue
    if [ -x "$dir/node" ]; then
        REAL_NODE="$dir/node"
        break
    fi
done
unset IFS
[ -n "$REAL_NODE" ] || REAL_NODE=/usr/local/bin/node

if [ "$OBSERVE" = "1" ] && [ -r "$PROBE" ]; then
    for arg in "$@"; do
        case "$arg" in
            *node_modules/*) break ;;
            -*) ;;
            *.js | *.cjs | *.mjs)
                exec "$REAL_NODE" --require "$PROBE" "$@"
                ;;
        esac
    done
fi

exec "$REAL_NODE" "$@"
