#!/bin/sh
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
# --------------------------------------------------------------------------------------------
#
# This script wraps the `node` commmand, and is used when Oryx needs to inject values to the node
# command line and the application is started using "npm start", or any other form where the
# node command is executed indirectly.
# We cannot use NODE_OPTIONS for instance, since for npm commands this variable would also apply
# and thus the debug port would be consumed for debugging npm itself instead of the application.
set -e

originalNodePath=/usr/local/bin/node
if [ -z "$ORYX_NODE_INSPECT_PARAM" ]; then
    inspectParameter="--inspect=0.0.0.0:9229"
else
    inspectParameter=$ORYX_NODE_INSPECT_PARAM
fi

targetScript="$1"
case $targetScript in
    # If the path is /usr/local, we asumme we're running an intermal library or tool, e.g. npm,
    # and not the app. In this case we run the node binary unchanged.
    "/usr/local/"*)
        $originalNodePath $@
        ;;
    *)
        injectDebugFlag=true
        args=""
        inspectFlag="--inspect"
        for param in "$@"; do
            case $param in
                # If the command already has --inspect as a parameter, we place it with our version of
                # it since we want to make sure the port is the one we expect.
                *"--inspect"*)
                    injectDebugFlag=false
                    args="$args $inspectParameter"
                    ;;
                *)
                    args="$args $param"
                    ;;
            esac
        done

        if [ "$injectDebugFlag" = "true" ]; then
            $originalNodePath $inspectParameter $@
        else
            $originalNodePath $args
        fi
        ;;
esac