#!/usr/bin/env bash
# Deploy this dev codebase to the wordpress.org SVN repo.
#
# Usage:
#   ./deploy-svn.sh "commit message"
#
# What it does:
#   1. Reads the plugin version from the `Version:` header of globaliser.php.
#   2. rsyncs the dev codebase into <SVN>/trunk, deleting anything that was
#      removed here since the last publish, and excluding dev-only files
#      (dotfiles, root *.md docs, this script itself).
#   3. Copies the fresh trunk contents into <SVN>/tags/<version>.
#   4. `cd`s into the SVN root and runs the WP.org publish dance:
#        svn add tags/<version>
#        svn add * --force
#        svn status
#        svn commit -m "<message>"
#
# Fails fast if the tag already exists so you don't accidentally overwrite
# a published release.

set -euo pipefail

if [ $# -lt 1 ]; then
    echo "Usage: $0 <commit-message>" >&2
    exit 1
fi

COMMIT_MSG="$1"

SRC="$(cd "$(dirname "$0")" && pwd)"
SVN_ROOT="/Users/selimkoc/Projects/wordpress.org/globaliser"
TRUNK="$SVN_ROOT/trunk"

if [ ! -d "$SVN_ROOT/.svn" ] && [ ! -d "$SVN_ROOT/tags" ]; then
    echo "Error: $SVN_ROOT does not look like an SVN checkout." >&2
    exit 1
fi

# Pull the plugin version straight out of the header line
#   Version: 0.9.15-dev.0.0.10
VERSION=$(grep -m1 -E '^\s*Version:' "$SRC/globaliser.php" \
          | sed -E 's/.*Version:[[:space:]]*//' \
          | tr -d '\r\n[:space:]')

if [ -z "$VERSION" ]; then
    echo "Error: could not extract Version from $SRC/globaliser.php" >&2
    exit 1
fi

TAG="$SVN_ROOT/tags/$VERSION"
if [ -d "$TAG" ]; then
    echo "Error: tag already exists at $TAG — bump the Version header first." >&2
    exit 1
fi

echo "Version:      $VERSION"
echo "Source:       $SRC"
echo "SVN root:     $SVN_ROOT"
echo "New tag:      tags/$VERSION"
echo

# rsync source → trunk.
#   --delete        remove files in trunk that were deleted here
#   /*.md           only ROOT-level *.md docs (dev-only); readme.txt stays,
#                   and any .md files nested inside subdirs (unlikely) stay too
#   deploy-svn.sh   don't ship the deploy script itself
#   .DS_Store       macOS turd, may appear at any depth
rsync -a --delete \
    --exclude '.git' \
    --exclude '.svn' \
    --exclude '.claude' \
    --exclude '.vscode' \
    --exclude '.dscode' \
    --exclude '.DS_Store' \
    --exclude '/*.md' \
    --exclude '/deploy-svn.sh' \
    "$SRC/" "$TRUNK/"

# Mirror the freshly-updated trunk into the new tag directory. Excluding
# .svn keeps trunk's working-copy metadata out of the tag payload.
mkdir -p "$TAG"
rsync -a --exclude '.svn' "$TRUNK/" "$TAG/"

cd "$SVN_ROOT"

echo
echo "→ svn add tags/$VERSION"
svn add "tags/$VERSION"

echo
echo "→ svn add * --force"
svn add * --force

echo
echo "→ svn status"
svn status

echo
echo "→ svn commit -m \"$COMMIT_MSG\""
svn commit -m "$COMMIT_MSG"

echo
echo "Done. Published $VERSION."
