#!/bin/bash
# ======================================
# WordPress Plugin Deploy Script
# Safe version with dry-run and commit mode
# ======================================

cd "$(dirname "$0")"

echo "Starting deploy check..."
echo "Working directory: $(pwd)"
echo

# Check if this is an SVN repo
if ! svn info > /dev/null 2>&1; then
  echo "Not an SVN working copy or no network connection."
  exit 1
fi

# Detect main plugin PHP file in trunk/
MAIN_FILE=$(find trunk -maxdepth 1 -name "*.php" | head -n 1)

if [ -z "$MAIN_FILE" ]; then
  echo "Could not find main plugin file in trunk/"
  exit 1
fi

# Extract version info safely (handles spaces/tabs)
PLUGIN_VERSION=$(grep -i "Version:" "$MAIN_FILE" | head -n 1 | sed -E 's/.*Version:[[:space:]]*([0-9.]+).*/\1/')
README_VERSION=$(grep -i "Stable tag:" trunk/readme.txt | awk '{print $3}')

echo "Detected main file: $MAIN_FILE"
echo "Plugin version: $PLUGIN_VERSION"
echo "Readme version: $README_VERSION"
echo

# Compare versions
if [ "$PLUGIN_VERSION" != "$README_VERSION" ]; then
  echo "Version mismatch!"
  echo "  Plugin header: $PLUGIN_VERSION"
  echo "  Readme stable tag: $README_VERSION"
  echo "  These must match before deploying."
  exit 1
else
  echo "Versions match — good to go."
fi

echo
echo "SVN status preview:"
svn status
echo

echo "Last commit message:"
svn log -l 1
echo

echo "Existing tags:"
svn list tags
echo

# If no commit flag, dry-run mode
if [ "$1" != "--commit" ]; then
  echo "Dry run complete — no changes were made."
  echo "To perform a real deploy, run: ./testsvn.sh --commit"
  exit 0
fi

# ======================================
# Safe commit section
# ======================================

# Check if tag already exists
if svn list tags | grep -q "$PLUGIN_VERSION/"; then
  echo "⚠️ Tag $PLUGIN_VERSION already exists. Please bump the version before deploying."
  exit 1
fi

echo
read -p "Are you sure you want to deploy version $PLUGIN_VERSION to WordPress.org? [y/N] " CONFIRM

if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
  echo "Aborted. No changes made."
  exit 0
fi

# Ask user for a custom message
echo
read -p "Enter a short commit message for this update: " USERMSG

echo
echo "Running deployment..."
echo "Staging changes..."
svn add --force * --auto-props --parents --depth infinity -q

echo
echo "Committing trunk with message: '$USERMSG'"
svn commit -m "$USERMSG"

echo
echo "Creating tag..."
svn cp trunk tags/$PLUGIN_VERSION

echo
echo "Committing tag with message: 'Tagging version $PLUGIN_VERSION'"
svn commit -m "Tagging version $PLUGIN_VERSION"

echo
echo "✅ Deployment complete! Version $PLUGIN_VERSION has been published."

