#! /usr/bin/env bash

export GITHUB_TOKEN="REDACTED"

branch=$1
pr_number=$(gh pr list -H $branch --json number | jq ".[0].number")

# testing if $pr_number is a number
if [ "$pr_number" -eq "$pr_number" ]; then
  echo "found PR: $pr_number"
  
  current_coverage=$(lcov --summary cover/lcov.info 2>&1 | grep lines | cut -d " " -f 4)
  current_tested_lines=$(lcov --summary cover/lcov.info 2>&1 | grep lines | cut -d "(" -f2 | cut -d " " -f 1)
  current_overall_lines=$(lcov --summary cover/lcov.info 2>&1 | grep lines | cut -d " " -f 7)
  body="Current branch test coverage is: <strong>$current_coverage</strong>"
  
  artifact pull project coverage/master/lcov.info --destination cover/lcov-master.info

  if [ -f cover/lcov-master.info ]; then  
    master_tested_lines=$(lcov --summary cover/lcov-master.info 2>&1 | grep lines | cut -d "(" -f2 | cut -d " " -f 1)
    master_overall_lines=$(lcov --summary cover/lcov-master.info 2>&1 | grep lines | cut -d " " -f 7)
    diff_coverage=$(calc "round((($current_tested_lines/$current_overall_lines) - ($master_tested_lines/$master_overall_lines)) * 100, 5)" | cut -f2)
    diff_zero=$(calc "$diff_coverage == 0")
    diff_sign=$(calc "$diff_coverage > 0")
    if [ $diff_zero -eq 1 ]; then
      body="$body<br>Coverage is unchanged (relative to master)"
    else
      if [ $diff_sign -eq 1 ]; then
        body="$body<br>Coverage is improving (relative to master): <strong>+$diff_coverage%</strong> 👍"
      else
        body="$body<br>Coverage is decreasing (relative to master): <strong>$diff_coverage%</strong> 👎"
      fi
    fi
  fi

  cache restore gh_coverage_comment_$branch

  # if a previous comment existed for current branch we will update it
  if [ -f GH_COVERAGE_COMMENT_URL ]; then  
    comment_url=$(cat GH_COVERAGE_COMMENT_URL)
    echo "updating existing comment $comment_url"
    gh api --method PATCH $comment_url -f body="$body"

  # otherwise we post a new comment and save its url
  else
    echo "posting a new comment"
    gh api --method POST /repos/team/project/issues/$pr_number/comments -f body="$body" | jq -r ".url" > GH_COVERAGE_COMMENT_URL
    cache delete gh_coverage_comment_$branch
    cache store gh_coverage_comment_$branch GH_COVERAGE_COMMENT_URL
  fi

else
  echo "no PR found for branch $branch"
fi