#!/bin/bash

cur_dir="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"

output_file="$cur_dir/../../doc/changelog/commit_changelog.txt"

true > "$output_file"

# Fetch the latest remote tags and refs
git fetch --tags origin

# Detect the default branch dynamically
default_branch=$(git remote show origin | grep 'HEAD branch' | awk '{print $NF}')

tags=$(git tag --sort=-v:refname)

previous_tag=""
for current_tag in $tags; do
    if [ -n "$previous_tag" ]; then
        echo "# Commits in $previous_tag" >> "$output_file"
        git log --pretty=format:"%h %s" "$current_tag..$previous_tag" --invert-grep --grep="^Merged in " >> "$output_file"
        echo -e "\n" >> "$output_file"
    fi
    previous_tag=$current_tag
done

# Include commits between the latest tag and the remote default branch
if [ -n "$previous_tag" ]; then
    echo "# Commits in $default_branch after $previous_tag" >> "$output_file"
    git log --pretty=format:"%h %s" "$previous_tag..origin/$default_branch" --invert-grep --grep="^Merged in " >> "$output_file"
fi

echo "Commit messages have been saved to $output_file."
