#!/bin/bash
# CI script to handle automatic version bumping
# Usage: scripts/ci-version-bump.sh <commit_message>

set -e

if [ -z "$1" ]; then
    echo "Error: Commit message not provided"
    exit 1
fi

LAST_COMMIT=$1
VERSION_BUMPED="false"

# Automatic version bump based on commit type
if echo "$LAST_COMMIT" | grep -q "^✨ feat:"; then
    echo "🎯 Feature commit detected - bumping MINOR version"
    ./scripts/version-bump.sh minor
    VERSION_BUMPED="true"
elif echo "$LAST_COMMIT" | grep -q "^🐛 fix:"; then
    echo "🐛 Fix commit detected - bumping PATCH version"
    ./scripts/version-bump.sh patch
    VERSION_BUMPED="true"
elif echo "$LAST_COMMIT" | grep -q "BREAKING CHANGE"; then
    echo "💥 Breaking change detected - bumping MAJOR version"
    ./scripts/version-bump.sh major
    VERSION_BUMPED="true"
else
    echo "⏭️  No automatic version bump needed"
fi

# Update swagger version regardless of bump
source VERSION
NEW_VERSION="$MAJOR.$MINOR.$PATCH${PRERELEASE:+-$PRERELEASE}"
sed -i "s|// @version [0-9.]*|// @version $NEW_VERSION|" cmd/server/main.go

# Commit version changes if bumped
if [ "$VERSION_BUMPED" = "true" ]; then
    git config --global user.name "CI Bot"
    git config --global user.email "ci@arcodange.fr"
    
    # Set up credentials using Gitea token
    if [ -n "$PACKAGES_TOKEN" ]; then
        git config --global credential.helper store
        echo "https://${PACKAGES_TOKEN}@gitea.arcodange.lab" > ~/.git-credentials
    fi
    
    git add VERSION cmd/server/main.go README.md
    if git commit -m "chore: auto version bump [skip ci]"; then
        # Try push with retry logic for race conditions
        for i in 1 2 3; do
            if git push; then
                echo "Successfully bumped version to $NEW_VERSION"
                exit 0
            else
                echo "Version bump push attempt $i failed, retrying..."
                if [ $i -eq 3 ]; then
                    echo "Final version bump push attempt failed - another job may have bumped version"
                    git pull --rebase || true
                    git push || echo "Version bump recovery push also failed"
                fi
                sleep 2
            fi
        done
    else
        echo "No version changes to commit"
    fi
fi