#!/bin/bash
source "$ROOT_PATH"/scripts/common.sh
set -eo pipefail

# Check if NEW_VERSION_NO_DIR is empty and set it to VERSION_TO_DEPLOY if it is
if [ -z "$NEW_VERSION_NO_DIR" ]; then
  NEW_VERSION_NO_DIR="$VERSION_TO_DEPLOY"
fi

if [ "${IS_MULTI_SERVICE_REPO}" = "true" ]; then  # multi service repo:
  echo_green "cd $LAMBDA_PATH :"
  cd "$LAMBDA_PATH" || handle_error "failed to cd $LAMBDA_PATH"
else
  echo_green "I assume this is mono service repo"
fi

# Prevent the script from exiting on errors
set +e

# Run npm version command and capture output and exit code
output=$(npm version "$NEW_VERSION_NO_DIR" --no-git-tag-version 2>&1)
exit_code=$?

# Restore default behavior of exiting on errors
set -e

# Print the captured output for debugging
echo "npm version output: $output"
echo "npm version exit code: $exit_code"

# Check if npm version command had an error
if [ $exit_code -eq 0 ]; then
    echo_green_bg "npm version command succeeded."
else
    # Check if the error is due to version not changed
    if [[ $output == *"npm ERR! Version not changed"* ]]; then
        echo_yellow "npm version command failed, but version not changed. Continuing..."
    else
        handle_error "npm version command failed due to some other issue. Exiting..."
    fi
fi
