#!/usr/bin/env bash
set -euo pipefail

if ! command -v bun >/dev/null 2>&1; then
  echo "agent-bar: bun is required but not found. Install it: https://bun.sh" >&2
  exit 1
fi

if [ -z "${NPM_CONFIG_TOKEN:-}" ]; then
  npmrc="${NPM_CONFIG_USERCONFIG:-$HOME/.npmrc}"
  if [ -f "$npmrc" ]; then
    token="$(sed -n 's#^//registry.npmjs.org/:_authToken=##p' "$npmrc" | head -n 1)"
    if [ -n "$token" ]; then
      export NPM_CONFIG_TOKEN="$token"
    fi
  fi
fi

if [ -z "${NPM_CONFIG_TOKEN:-}" ]; then
  echo "agent-bar: npm auth token not found for Bun publish." >&2
  echo "Run \`bunx npm login\` or export NPM_CONFIG_TOKEN, then retry." >&2
  exit 1
fi

exec bun publish "$@"
