#!/bin/bash

# Initialize the files, vars and the git data:
git config --global user.email "svc-github@perimeter81.com"
git config --global user.name "Sayuser"

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


change_log="false"
pom_xml="false"
to_commit="false"

git fetch --tags
last_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
echo "all the commits until last tag $last_tag"
git log --pretty=format:"%s" HEAD...$last_tag  > tmp_release_notes.txt
git log --pretty=format:"%s" HEAD...$last_tag  > tag_release_notes.txt
echo 1
cat tmp_release_notes.txt
echo "1.5"
cat tag_release_notes.txt
echo -e "\n" >> tag_release_notes.txt
echo "build $BUILD_NUMBER from GITHUB ACTIONS on $(date):" >> tag_release_notes.txt
# echo "https://ci.safersoftware.net/viewLog.html?buildId=$BUILD_NUMBER" >> tag_release_notes.txt
echo "by jira https://perimeter81.atlassian.net/browse/${JIRA_TICKET}" >> tag_release_notes.txt
echo "1.6"
cat tag_release_notes.txt
sed -i 's/^/- /' tmp_release_notes.txt
echo -e "\n" >> tmp_release_notes.txt

if [ -f "CHANGELOG.md" ]; then
  sed -i "7 i ## [$NEW_VERSION] - $(date +%F)" CHANGELOG.md
  sed -i "8 i ### Added" CHANGELOG.md
  sed -i "8r $$DIR_TO_BUILD/tmp_release_notes.txt" CHANGELOG.md
  to_commit="true"
  change_log="true"
fi

cd $DIR_TO_BUILD

if [ -f "pom.xml" ]; then
  n_version="${NEW_VERSION_NO_DIR:1}"
  echo "new version: $n_version"
  xml_path=".project.properties.revision=\"$n_version\""

  yq -p xml -o xml -i $xml_path pom.xml
  yq -p xml '.project.properties.revision' pom.xml
  to_commit="true"
  pom_xml="true"
fi

if [ $to_commit = "true" ]; then
  # echo "##teamcity[setParameter name='env.PUSH_TAG' value='$to_commit']"
  echo 2
  if [ $change_log = "true" ]; then
    cd ../
    git add CHANGELOG.md
    cd $DIR_TO_BUILD
  fi
  if [ $pom_xml = "true" ]; then
    git add pom.xml
  fi
  echo 5
  echo commiting the changes
  git commit -m "update CHANGELOG.md and package.json"
  echo done commiting
  echo taging the new commit with tag $NEW_VERSION
  git tag $NEW_VERSION
  echo done tagging
  echo 6
fi

# rm tag_release_notes.txt