#!/bin/bash

git config --global user.email "svc-github@perimeter81.com"
git config --global user.name "Sayuser"

PR_NUMBER="$1"
REPO_NAME="$2"

git fetch --tags >/dev/null 2>&1

# get last tag:
last_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
echo "last tag: $last_tag"

# get commit messages until the last tag:
if [ -z "$CHANGELOG_DESCRIPTION" ]; then
  git log --pretty=format:"%s" HEAD...$last_tag  > tmp_release_notes.txt
  sed -i 's/^/- /' tmp_release_notes.txt
  echo "the number of commits until the last tag $last_tag is: $(cat tmp_release_notes.txt | wc -l)"
else
  echo "merged from PR [#$PR_NUMBER](https://github.com/$REPO_NAME/pull/$PR_NUMBER)" >> tmp_release_notes.txt
  echo "release notes:"
  cat tmp_release_notes.txt
  echo "end of release notes"
fi
echo -e "\n" >> tmp_release_notes.txt

git log --pretty=format:"%s" HEAD...$last_tag  > tag_release_notes.txt

# add info to release notes
echo -e "\n" >> tag_release_notes.txt
echo "build $BUILD_NUMBER from github actions on $(date):" >> tag_release_notes.txt
echo "merged from PR (#$PR_NUMBER)" >> tag_release_notes.txt
echo "by jira https://perimeter81.atlassian.net/browse/${JIRA_TICKET}" >> tag_release_notes.txt

# Determine the version information
if [ -n "$NEW_VERSION" ] && [ -n "$NEW_ENV_VERSION" ]; then
  VERSION="$NEW_VERSION | $NEW_ENV_VERSION"
elif [ -n "$NEW_VERSION" ]; then
  VERSION="$NEW_VERSION"
elif [ -n "$NEW_ENV_VERSION" ]; then
  VERSION="$NEW_ENV_VERSION"
else
  VERSION=""
fi

echo "Version is : $VERSION"

# Check if CHANGELOG.md exists
if [ -f "CHANGELOG.md" ]; then
  echo "CHANGELOG.md exists. Prepending release notes to changelog.md:"
  # Prepend release notes to CHANGELOG.md
  { echo -e "## [$VERSION] - $(date +%F)\n### Added"; cat tmp_release_notes.txt; cat CHANGELOG.md; } > temp && mv temp CHANGELOG.md
  cat CHANGELOG.md
  echo "done prepending release notes to CHANGELOG.md"
else
  echo "CHANGELOG.md doesn't exist. Creating new CHANGELOG.md file."
  # Create new CHANGELOG.md file
  echo -e "## [$VERSION] - $(date +%F)\n### Added" > CHANGELOG.md
  cat tmp_release_notes.txt >> CHANGELOG.md
  echo "done creating new CHANGELOG.md file"
fi

echo "git add changelog:"
git add CHANGELOG.md
echo "done git add, commit, and push for changelog"
