#!/bin/bash

# Check the number of parameters
if [ "$#" -ne 1 ]; then
    echo "Error: You must specify exactly one parameter."
    echo "Specify task name without dash as parameter (e.g., XM1234 or XM12345)."
    exit 1
fi

# Parameter validation
REGEX="^XM[0-9]{4,5}$"

if [[ ! "$1" =~ $REGEX ]]; then
    echo "Error: The parameter '$1' is not valid."
    echo "It must start with 'XM' followed by 4 or 5 digits (e.g., XM1234 or XM12345)."
    exit 1
fi

task_name=$1

# Abort if pending changes are present in the working area
git_status=$(git status --porcelain)
if [[ -n "$git_status" ]]; then
  echo "There are pending changes in the working directory."
  echo "Script execution will be aborted."
  exit 1
fi

# Get the version of the package
package_version=$(cat package.json \
  | grep version \
  | head -1 \
  | awk -F: '{ print $2 }' \
  | sed 's/[",]//g' \
  | tr -d '[[:space:]]')

# Get SemVer from package version
sem_ver=$(echo "$package_version" | grep -o '^[^-]*')

# Generate timestamp
timestamp=$(date +%s)

# Update the version of the package
npm version $sem_ver-$task_name-$timestamp --no-git-tag-version

# Install dependencies
pnpm i

# Publish the package
npm publish --tag $task_name
PUBLISH_EXIT_CODE=$?

# Clean changes to package.json
git checkout package.json

# Check if publish failed
if [ $PUBLISH_EXIT_CODE -ne 0 ]; then
    echo ""
    echo "Error: npm publish failed with code $PUBLISH_EXIT_CODE"
    exit $PUBLISH_EXIT_CODE
fi

# # Print the installation command of the published packaged
printf "\nPackage successfully published."
printf "\nInstall it using the following command:"
printf "\npnpm i --save-exact xcally-nest-library@$sem_ver-$task_name-$timestamp\n\n"
