#!/bin/bash
set -e

VERSION="$1"

if [ -z "$VERSION" ]; then
	echo "Usage: $0 <version>"
	exit 1
fi

TAG_DIR="tags/$VERSION"

if [ ! -d "$TAG_DIR" ]; then
	echo "Error: directory $TAG_DIR does not exist."
	exit 1
fi

# helper: check if a path is already under version control
is_versioned() {
	svn info "$1" &>/dev/null
}

# helper: commit with svn update to avoid "out of date" errors
safe_commit() {
	local msg="$1"
	svn update --accept postpone
	svn commit -m "$msg"
}

# --- Step 1: source code (everything except vendor internals) ---
if ! is_versioned "$TAG_DIR"; then
	echo "Adding tag directory $TAG_DIR..."
	svn add "$TAG_DIR"
	svn revert "$TAG_DIR/vendor" --depth infinity
	svn add "$TAG_DIR/vendor" --depth empty
	svn add "$TAG_DIR/vendor/autoload.php"

	echo "Committing source code for version $VERSION..."
	safe_commit "add version $VERSION source code"
	echo "Source code committed successfully."
else
	echo "Tag directory $TAG_DIR already versioned, skipping source code step."
fi

# --- Step 2: vendor folders in batches ---
folders=("$TAG_DIR"/vendor/*/)
total=${#folders[@]}

count=0
skipped=0
for d in "${folders[@]}"; do
	((count++))
	name=$(basename "$d")

	if is_versioned "$d"; then
		((skipped++))
		echo "[$count/$total] Skipping vendor/$name (already committed)"
		continue
	fi

	echo "[$count/$total] Adding and committing vendor/$name..."
	svn add "$d"
	if ! safe_commit "add vendor folder $name for version $VERSION"; then
		echo ""
		echo "ERROR: failed to commit vendor/$name."
		echo "Fix the issue and re-run the script to resume from this point."
		exit 1
	fi
done

echo ""
echo "All commits for version $VERSION completed. ($skipped skipped, $((count - skipped)) committed)"
