#!/bin/bash

#show current branch
current_branch="$(git rev-parse --abbrev-ref HEAD)"

title="$(tr '[:lower:]' '[:upper:]' <<< ${current_branch:0:1})${current_branch:1}"

origin="https://github.com/tidbcloud/management-portal-ui"
issue_link="$origin/pull"
commit_link=$origin/commit
jira_link="https://tidb.atlassian.net/browse"

all_commits=$(git log master.. --pretty=format:"%H %s")

NL=$'\n'

contents="# $title$NL"

function replace_issue() {
  re='(.*)#([0-9]+)(.*)'
  if [[ $1 =~ $re ]]; then
    echo "${BASH_REMATCH[1]}[#${BASH_REMATCH[2]}]($issue_link/${BASH_REMATCH[2]})${BASH_REMATCH[3]}"
  else
    echo "$1"
  fi
}

function replace_jira() {
  re='(.*)DM-([0-9]+)(.*)'
  if [[ $1 =~ $re ]]; then
    echo "${BASH_REMATCH[1]}[DM-${BASH_REMATCH[2]}]($jira_link/DM-${BASH_REMATCH[2]})${BASH_REMATCH[3]}"
  else
    echo "$1"
  fi
}

echo "$all_commits" |
{
  while read line; do
    # extract hash and description
    re='([0-9a-z]+)[[:space:]](.*)'
    if [[ $line =~ $re ]]; then
      hash=" [${BASH_REMATCH[1]:0:8}]($commit_link/${BASH_REMATCH[1]})"
      description=${BASH_REMATCH[2]}
    else
      hash=""
      description=$line
    fi

    if [[ $description =~ ^Merge ]]; then
      rl="$(replace_issue "$description")"
      rl="$(replace_jira "$rl")"
      contents="$contents* $rl$hash$NL$NL"
    else
      contents="$contents  * $description$hash$NL$NL"
    fi
  done
  echo "$contents" > ./changelog/$current_branch.md
}

