#!/bin/bash
# This script is used to release a new version of depi-node-client - for the server see ../../release.sh
# Run from the node-client directory: ./release.sh [-p|--push] <VERSION>
PUSH=false
VERSION=""

cd "$(dirname "${BASH_SOURCE[0]}")"

while [[ $# -gt 0 ]]; do
  case "$1" in
    -p|--push)
      PUSH=true
      shift
      ;;
    -*)
      echo "Error: Unknown option: $1"
      echo "Usage: $0 [-p|--push] <VERSION>"
      exit 1
      ;;
    *)
      if [ -n "$VERSION" ]; then
        echo "Error: Unexpected argument: $1"
        echo "Usage: $0 [-p|--push] <VERSION>"
        exit 1
      fi
      VERSION=$1
      shift
      ;;
  esac
done

if [ -z "$VERSION" ]; then
  echo "Error: VERSION argument is required."
  echo "Usage: $0 [-p|--push] <VERSION>"
  exit 1
fi

echo "VERSION is set to: $VERSION"

# Check that VERSION matches the pattern x.x.x where x is a non-negative integer (allows 0)
if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  echo "Error: VERSION must be in the format x.x.x where x is a non-negative integer (e.g., 0.1.2)"
  exit 1
fi

npm version "$VERSION" --no-git-tag-version
git add package.json package-lock.json
git commit -m "Node-client release $VERSION"
TAG="node-client/$VERSION"
git tag "$TAG"

if [ "$PUSH" = true ]; then
  git push origin main && git push origin "$TAG"
  echo "✅ All done! Committed, tagged $TAG, and pushed to origin."
else
  echo "✅ All done! Committed and created tag $TAG! Please push with:"
  echo ""
  echo "git push origin main && git push origin $TAG"
fi

echo ""
echo "📦 Publish to npm:"
echo ""
echo "  npm publish"
