#!/bin/bash

set -euo pipefail
IFS=$'\n\t'

RELEASE_TYPE=${1:-}

echo_help() {
  cat << EOF
USAGE:
    ./scripts/publish <release_type>

ARGS:
    <release_type>
            A Semantic Versioning release type used to bump the version number. Either "patch", "minor", or "major".
EOF
}

# Show help if no arguments passed
if [ $# -eq 0 ]; then
  echo "Error! Missing release type argument"
  echo ""
  echo_help
  exit 1
fi

# Show help message if -h, --help, or help passed
case $1 in
  -h | --help | help)
    echo_help
    exit 0
    ;;
esac

# Validate passed release type
case $RELEASE_TYPE in
  patch | minor | major)
    ;;

  *)
    echo "Error! Invalid release type supplied"
    echo ""
    echo_help
    exit 1
    ;;
esac

# Make sure our working dir is the modelcontextprotocol directory
cd "$(git rev-parse --show-toplevel)/modelcontextprotocol"

echo "Fetching git remotes"
git fetch

GIT_STATUS=$(git status)

if ! grep -q 'On branch main' <<< "$GIT_STATUS"; then
  echo "Error! Must be on main branch to publish"
  exit 1
fi

if ! grep -q "Your branch is up to date with 'origin/main'." <<< "$GIT_STATUS"; then
  echo "Error! Must be up to date with origin/main to publish"
  exit 1
fi

if ! grep -q 'working tree clean' <<< "$GIT_STATUS"; then
  echo "Error! Cannot publish with dirty working tree"
  exit 1
fi

echo "Installing dependencies according to lockfile"
pnpm install --frozen-lockfile

echo "Running tests"
pnpm run test

echo "Building package"
pnpm run build

echo "Publishing release"
npm --ignore-scripts publish --non-interactive

echo "Pushing git commit and tag"
git push

echo "Clean"
pnpm run clean

echo "Publish successful!"
echo ""
