#!/bin/bash

echo "Running versionBuild.sh..."

# Version bump part
if [[ $CI_COMMIT_BRANCH == "main" ]]; then
  VERSION_FILE="VERSION_main"
else
  VERSION_FILE="VERSION_staging"
fi
echo "Using VERSION_FILE: $VERSION_FILE"

echo "Reading current version from $VERSION_FILE..."
current_version=$(cat $VERSION_FILE)
echo "Current version: $current_version"

# Get commit messages from the last 5 commits
commit_messages=$(git log -n 5 --format=%B)
if [[ $current_commit_message == *"[Automated] Bump version to"* ]]; then
  echo "Skipping version bump. Current commit is already a version bump commit."
  exit 0
fi

IFS='.' read -ra VERSION_COMPONENTS <<< "$current_version"
major=${VERSION_COMPONENTS[0]}
minor=${VERSION_COMPONENTS[1]}
patch=${VERSION_COMPONENTS[2]}
echo "Major: $major, Minor: $minor, Patch: $patch"

# Get commit messages since the last version bump
last_version_bump=$(git log --grep="\[Automated\] Bump version to" -n 1 --pretty=format:%H)
if [ -z "$last_version_bump" ]; then
  echo "No previous version bump found. Getting all commit messages."
  commit_messages=$(git log --format=%B)
else
  echo "Getting commit messages since last version bump."
  commit_messages=$(git log ${last_version_bump}..HEAD --format=%B)
fi

echo "Commit messages:"
echo "$commit_messages"

found_change=false
matched_commit=""
while IFS= read -r line; do
  echo "Processing commit message: $line"
  if [[ $line == *"BREAKING CHANGE"* ]]; then
    echo "Found BREAKING CHANGE. Incrementing major version..."
    major=$((major + 1))
    minor=0
    patch=0
    found_change=true
    matched_commit=$line
    break
  elif [[ $line == *"changing"* ]]; then
    echo "Found feat. Incrementing minor version..."
    minor=$((minor + 1))
    patch=0
    found_change=true
    matched_commit=$line
    break
  elif [[ $line == *"fixing"* ]]; then
    echo "Found fix. Incrementing patch version..."
    patch=$((patch + 1))
    found_change=true
    matched_commit=$line
    break
  fi
done <<< "$commit_messages"

new_version="$major.$minor.$patch"
if $found_change; then
  echo "Setting new version: $new_version in $VERSION_FILE..."
  echo $new_version > $VERSION_FILE
  echo "Old version: $current_version"
  echo "New version: $new_version"
  echo "Matched commit message: $matched_commit"
  git add $VERSION_FILE
  git config user.email "$GITLAB_USER_EMAIL"
  git config user.name "$GITLAB_USER_NAME"
  git commit -m "[Automated] Bump version to $new_version"
  # Use API token for push
  git push https://oauth2:<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>/akram.kamoun/acre.git HEAD:$CI_COMMIT_BRANCH
else
  echo "No changes found to warrant a version bump."
  new_version=$current_version
fi

echo "Version bump script completed."

# Build part
set -e

# Error Handling Function
handle_error() {
    echo "ERROR: $1"
    exit 1
}

# Append branch name to version
FULL_VERSION="${new_version}-${CI_COMMIT_BRANCH}"

# Update the version in GitLab CI/CD variable
curl --request PUT \
     --header "PRIVATE-TOKEN: <TRUFFLEHOG_REDACTED_GITLAB>" \
     --header "Content-Type: application/json" \
     --data '{
       "value": "'"$FULL_VERSION"'",
       "protected": false,
       "masked": false,
       "environment_scope": "'"$CI_COMMIT_BRANCH"'"
     }' \
     "https://gitlab.com/api/v4/projects/58427295/variables/version"

echo "Updated CI/CD is a  variable version to: $FULL_VERSION"

chmod +x ./mvnw || handle_error "Failed to make mvnw executable"

# Build Docker image with Maven Jib and capture output
./mvnw -T 1C package -Pprod,api-docs jib:dockerBuild -DskipTests -Dmaven.test.skip=true -Darchunit.skip=true -Dmaven.javadoc.skip=true -Dmaven.source.skip=true -Drevision=$FULL_VERSION -Djib.to.image=acre:latest -Dmaven.repo.local=.m2/repository


# Docker login using predefined CI/CD variables
echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY

# Tagging strategy
docker tag acre "$CI_REGISTRY_IMAGE:$FULL_VERSION" || handle_error "Failed to tag image with version and branch"
if [[ $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "staging" ]]; then
  docker tag acre "$CI_REGISTRY_IMAGE:latest-$CI_COMMIT_BRANCH" || handle_error "Failed to tag image with 'latest' and branch"
fi

# Push images to registry 
docker push "$CI_REGISTRY_IMAGE:$FULL_VERSION" || handle_error "Failed to push image with version and branch"
if [[ $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH == "staging" ]]; then
  docker push "$CI_REGISTRY_IMAGE:latest-$CI_COMMIT_BRANCH" || handle_error "Failed to push image with 'latest' and branch"
fi

echo "Successfully built and pushed Docker images"
recreate full compleetd combined yml and use services external ip also for conenctivity and why generatot hsa ti add the custom atributes also i want only the process add and returns it 
so do your analyse and give full logical completed combined yml + your logic how i t works