#!/usr/bin/env bash

set -Eeuo pipefail

readonly REGISTRY="https://registry.npmjs.org/"
readonly PACKAGE_NAME="@appconda/sdk"
readonly SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"

cd "$SCRIPT_DIR"

# Authenticate before changing package.json so an expired credential cannot
# leave behind another unused version bump.
if ! NPM_USER="$(npm whoami --registry "$REGISTRY" 2>/dev/null)"; then
  USER_CONFIG="$(npm config get userconfig)"
  cat >&2 <<EOF
No valid npm credential was found in $USER_CONFIG.

For local publishing, save a granular access token with read/write access to
$PACKAGE_NAME in that user-level npmrc. A regular "npm login" session expires
after two hours and will require browser approval again.
EOF
  exit 1
fi

ACTUAL_PACKAGE_NAME="$(node -p "require('./package.json').name")"
if [[ "$ACTUAL_PACKAGE_NAME" != "$PACKAGE_NAME" ]]; then
  printf 'Refusing to publish unexpected package: %s\n' "$ACTUAL_PACKAGE_NAME" >&2
  exit 1
fi

printf 'Authenticated to npm as %s.\n' "$NPM_USER"

# Build first; only increment the persisted version after the build succeeds.
npm run build
npm version patch -m "Upgrade to new version" --no-git-tag-version
npm publish --access public --registry "$REGISTRY"
