#!/bin/bash
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
# This file is a simple wrapper around whatever machine-specific version
# of `npm` we downloaded (as part of Node).
set -euo pipefail

SCRIPT_DIR="$(cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd)"

platform=$(uname -s)
arch=$(uname -m)
key="${platform}-${arch}"

node_path=""
case "${key}" in
  Darwin-x86_64)
    node_path="mac/node-darwin-x64"
    ;;
  Darwin-arm64)
    node_path="mac_arm64/node-darwin-arm64"
    ;;
  Linux-x86_64)
    node_path="linux/node-linux-x64"
    ;;
  *)
    echo "Unsupported system: ${key}" >&2
    exit 1
    ;;
esac

node_dir="${SCRIPT_DIR}/third_party/node/${node_path}"

if [[ ! -d "${node_dir}" ]]; then
  echo "Missing node binary directory: ${node_dir}" >&2
  exit 1
fi

export PATH="${node_dir}/bin:${SCRIPT_DIR}/node_modules/.bin:${PATH}"

npm_cli="${SCRIPT_DIR}/node_modules/npm/bin/npm-cli.js"
exec "${node_dir}/bin/node" "${npm_cli}" run-script "$@"
