#!/bin/bash

# Fetch the latest changes from the remote repository
git fetch

# Get the name of the current branch
current_branch=$(git branch --show-current)

# Ensure we're in a git repository and have a valid branch
if [ -z "$current_branch" ]; then
  echo "Error: Not in a valid git repository or on a detached head."
  exit 1
fi

echo "Current branch: $current_branch"

# Get a list of all branches except the current branch and dev
branches=$(git branch --format='%(refname:short)' | grep -v -E "(^${current_branch}$|^dev$|^main$)")

for branch in $branches; do
  # Check if the branch has been merged into the current branch
  if ! git branch --merged "$current_branch" | grep -q "$branch"; then
    echo "Merging branch $branch into $current_branch"
    git merge "$branch"

    # Check if the merge was successful
    if [ $? -ne 0 ]; then
      echo "Conflict encountered. Please resolve conflicts and run the script again."
      exit 1
    fi
  fi
done

echo "All relevant branches have been merged into $current_branch."
