#!/bin/bash

# ANSI color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}🔒 Preparing BWS Secure for npm publication${NC}"

# Make sure we're in the repository root
if [ ! -f "secureRun.js" ]; then
  echo -e "${RED}❌ Error: This script must be run from the repository root${NC}"
  exit 1
fi

# Make bin directory if it doesn't exist
if [ ! -d "bin" ]; then
  echo "Creating bin directory..."
  mkdir -p bin
fi

# Make all bin scripts executable
chmod +x bin/*

# Copy NPM-README.md to README.md temporarily for npm publish
if [ -f "NPM-README.md" ]; then
  echo "Backing up original README.md..."
  cp README.md README.md.backup
  
  echo "Using NPM-README.md for publication..."
  cp NPM-README.md README.md
fi

# Remove node_modules if exists to avoid including it in the package
if [ -d "node_modules" ]; then
  echo "Backing up node_modules..."
  mv node_modules node_modules.backup
fi

# Check if this is a beta version
VERSION=$(node -e "console.log(require('./package.json').version)")
if [[ "$VERSION" == *beta* ]]; then
  echo -e "${GREEN}Publishing beta version to npm with beta tag...${NC}"
  npm publish --tag beta
else
  echo -e "${GREEN}Publishing to npm...${NC}"
  npm publish
fi

# Restore node_modules if it was backed up
if [ -d "node_modules.backup" ]; then
  echo "Restoring node_modules..."
  mv node_modules.backup node_modules
fi

# Restore original README.md
if [ -f "README.md.backup" ]; then
  echo "Restoring original README.md..."
  mv README.md.backup README.md
fi

echo -e "${GREEN}✅ BWS Secure has been published to npm${NC}" 