#!/bin/bash

set -euo pipefail

# CONFIGURATION
REGISTRY="docker.botris.dev"
USERNAME="johnbotris"
IMAGE_NAME="femto-api"
DOCKERFILE_PATH="Femto.Api/Dockerfile"
BUILD_CONTEXT="."
BUILD_CONFIGURATION="Release"
PROPS_FILE="Directory.Build.props"

# Step 0: Ensure clean working directory
if [[ -n $(git status --porcelain) ]]; then
  echo "❌ Uncommitted changes detected. Please commit or stash them before running this script."
  exit 1
fi

# Step 1: Extract current version
OLD_VERSION=$(xmllint --xpath "string(//Project/PropertyGroup/Version)" $PROPS_FILE)
echo "🔍 Current version: $OLD_VERSION"

# Step 2: Bump patch version (you can change this to minor/major)
IFS='.' read -r MAJOR MINOR PATCH <<< "$OLD_VERSION"
PATCH=$((PATCH + 1))
NEW_VERSION="$MAJOR.$MINOR.$PATCH"

echo "🚀 Bumping version to $NEW_VERSION..."
# Update version in Directory.Build.props
sed -i.bak "s|<Version>$OLD_VERSION</Version>|<Version>$NEW_VERSION</Version>|" $PROPS_FILE
rm "${PROPS_FILE}.bak"

# Step 3: Attempt Docker build
FULL_IMAGE="$REGISTRY/$USERNAME/$IMAGE_NAME"
echo "🔧 Building Docker image..."
if ! docker build -f "$DOCKERFILE_PATH" "$BUILD_CONTEXT" -t "$IMAGE_NAME"; then
  echo "❌ Docker build failed. Reverting version..."
  git checkout -- "$PROPS_FILE"
  exit 1
fi

# Step 4: Tag and push Docker image
echo "🏷️ Tagging Docker image..."
docker tag "$IMAGE_NAME" "$FULL_IMAGE:$NEW_VERSION"
docker tag "$IMAGE_NAME" "$FULL_IMAGE:latest"

echo "📤 Pushing Docker images..."
docker push "$FULL_IMAGE:$NEW_VERSION"
docker push "$FULL_IMAGE:latest"

# Step 5: Commit version bump & tag
echo "✅ Committing and tagging version bump..."
git add "$PROPS_FILE"
git commit -m "chore(release): v$NEW_VERSION"
git tag "v$NEW_VERSION"
git push origin main
git push origin "v$NEW_VERSION"

echo "🎉 Release v$NEW_VERSION complete."

