#!/usr/bin/env bash

SCRIPT_PATH=$( cd "$(dirname "$0")" ; pwd -P )

SERVICE_NAME="node-interpretter"

source ${SCRIPT_PATH}/shared.env.shinc 2> /dev/null
source ${SCRIPT_PATH}/env.shinc 2> /dev/null


docker inspect --type container ${SERVICE_NAME} > /dev/null 2>&1

if [[ $? -ne 0 ]]; then
	echo "The node container does not exist"
	exit 137
fi

NODE_SERVICE_STATE=$(docker inspect --type container ${SERVICE_NAME} --format "{{.State.Running}}")
if [[ $? -ne 0 ]]; then
	echo "Could not get state of the node container"
	exit 137
fi

if [[ "${NODE_SERVICE_STATE}" != "true" ]]; then
	docker start ${SERVICE_NAME} > /dev/null 2>&1

	if [[ $? -ne 0 ]]; then
		echo "Could not start the node container"
		exit 137
	fi
fi


case "${1}" in
	npm|npx|yarn|yarnpkg|*npm-cli.js*|*npx-cli.js*)
		docker exec -i ${SERVICE_NAME} "$@"
		;;
	*)
		docker exec -i ${SERVICE_NAME} node "$@"
		;;
esac
