#!/bin/bash
#
# Copyright 2016 The Kubernetes Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Set PROGram name
PROG=${0##*/}
########################################################################
#+
#+ NAME
#+     $PROG - Generate release notes for K8S releases
#+
#+ SYNOPSIS
#+     $PROG  [--quiet] [[starttag..]endtag] [--htmlize-md] [--full]
#+            [--github-token=<token>] [--branch=<branch>]
#+            [--markdown-file=<file>] [--html-file=<file>]
#+            [--preview] [--verbose]
#+     $PROG  [--helpshort|--usage|-?]
#+     $PROG  [--help|-man]
#+
#+ DESCRIPTION
#+      $PROG scans 'git log' for 'merge pull's and collects and displays
#+      release notes based on release-note-* labels from PR titles and PR
#+      release-note blocks (in the body).
#+
#+      By default, $PROG produces release notes for the last github release
#+      to the HEAD of current branch and uses a standard git range otherwise.
#+      You may omit the end of the range to terminate the range at the HEAD
#+      of the current branch.
#+
#+      The default output is pure markdown and unless [--markdown-file=] is
#+      specified, the output file is in /tmp/$PROG-release-notes.md.
#+      If [--html-file=] is set, $PROG will also produce a pure html version
#+      of the notes at that location.
#+
#+      If [--quiet] is not specified, the output to stdout will always be
#+      only the markdown version of the output.
#+
#+      [--branch=] is used to specify a branch other than the current one.
#+
#+      Other options detailed in EXAMPLES below.
#+
#+ OPTIONS
#+     --quiet                   - Don't display the notes when done
#+     --htmlize-md              - Output markdown with html for PRs and
#+                                 contributors (for use in CHANGELOG-x.y.md)
#+     --full                    - Force 'full' release format to show all
#+                                 sections of release notes. (This is the
#+                                 *default* for new branch X.Y.0 notes)
#+     --markdown-file=          - Specify an alt file to use to store notes
#+     --html-file=              - Produce a html version of the notes
#+     --preview                 - Report additional branch statistics (used for
#+                                 reporting outside of releases)
#+     --github-token=           - Must be specified if GITHUB_TOKEN not set
#+     --branch=                 - Specify a branch other than the current one
#+     [--help | -man]           - Display man page for this script
#+     [--usage | -?]            - Display in-line usage
#+
#+ EXAMPLES
#+     $PROG                     - Notes for last release to HEAD
#+                                 on current branch
#+     $PROG v1.1.4..            - Notes for v1.1.4 to HEAD on current branch
#+     $PROG v1.1.4..v1.1.7      - Notes for v1.1.4..v1.1.7
#+     $PROG v1.1.7              - Notes for last release
#+                                 on current branch to v1.1.7
#+
#+ FILES
#+     /tmp/$PROG-release-htmls.md
#+     /tmp/$PROG-release-htmls.html
#+
#+ SEE ALSO
#+     common.sh                 - Base function definitions
#+     gitlib.sh                 - git-related function definitions
#+     https://stedolan.github.io/jq - JSON CLI
#+
#+ BUGS/TODO
#+
########################################################################
# If NO ARGUMENTS should return *usage*, uncomment the following line:
#usage=${1-yes}

source $(dirname $(readlink -ne $BASH_SOURCE))/lib/common.sh
source $TOOL_LIB_PATH/gitlib.sh

# Validate command-line
common::argc_validate 2

###############################################################################
# FUNCTIONS
###############################################################################
###############################################################################
# Get titles from a list of PRs
# @param prs - A space separated list of PRs to extract
#
extract_pr_title () {
  local prs="$*"
  local pr
  local content
  local body
  local author
  local pull_json

  for pr in $prs; do
    pull_json="$($GHCURL $CILIUM_GITHUB_API/pulls/$pr)"
    [[ -z "$pull_json" ]] && return 1
    body="$(echo "$pull_json" |jq -r '.body' |tr -d '\r')"

    # Look for a body release note first and default to title
    # * indent lines >1
    # Try to account for and adjust user-entered formatting
    # * This is somewhat complicated by the fact that we convert this to
    #   html, for things like email, group posts, dashboards, and there
    #   is a disconnect between pandoc and github's markdown for lists.
    #   https://github.com/jgm/pandoc/issues/2210
    content=$(echo "$body" |\
              sed -n '/^``` *release-note/,/^```/{/^```/!p;/^```$/q}' |\
              sed -e '/^$/d' -e '2,$s/^\( *\* \)/        \1/g' \
                  -e '2,$s/^\( *[^ \*]\)/    * \1/g')

    # if the release-note block is empty (unchanged from the template), use title
    if [[ -z "$content" ]]; then
      content=$(echo "$pull_json" | jq -r '.title')
    fi

    author=$(echo "$pull_json" | jq -r '.user.login')
    content=$(echo "$content" |sed -e '1s/^ *\** */* /g' \
                                   -e "1s/$/ (#$pr, @$author)/g")

    logecho -r "$content"
  done
}

###############################################################################
# Get merged PRs that match a specified label
get_prs () {
  local label=$1
  local -a prs
  local total
  local current_page
  local num_pages
  local prs_per_page
  local url

  prs_per_page=100

  url="https://api.github.com/search/issues?per_page=1&q=is:pr%20repo:cilium/cilium%20is:closed%20label:$label"
  total="$($GHCURL $url | jq -r '.total_count')"

  # Calculate number of pages, rounding up
  num_pages=$(((total + prs_per_page - 1) / prs_per_page ))

  for current_page in `seq 1 $num_pages`; do
    prs+=($($GHCURL "${CILIUM_GITHUB_SEARCHAPI}label:${label}&page=$current_page" | jq -r '.items[] | (.number | tostring)'))
  done

  echo "${prs[@]}"
}


###############################################################################
# Create the release note markdown body
# @param release_tars - A directory containing tarballs to link to on GCS
# @param start_tag - The start tag of range
# @param release_tag - The release tag of range
#
create_body () {
  local release_tars=$1
  local start_tag=$2
  local release_tag=$3
  local title

  ((FLAGS_preview)) && title="Branch "
  # Show a more useful header if release_tag == HEAD
  if [[ "$release_tag" == "HEAD" ]]; then
    title+=$CURRENT_BRANCH
  else
    title+=$release_tag
  fi

  ((FLAGS_preview)) && echo "**Release Note Preview - generated on $(date)**"
  echo
  echo "# $title"
  echo
  cat $PR_NOTES
}


###############################################################################
# Returns true if the SHA is within the git revision range
commit_in_release() {
  local sha="$1"
  local range="$2"

  echo $sha $range

  git log --pretty=oneline "$range" 2> /dev/null | grep "$sha" > /dev/null 2>&1
}

###############################################################################
# Generates the release notes for one particular PR
generate_release_note_for_pr () {
  local pr=$1
  local url
  local pr_json
  local merge_sha
  local merged_at

  url="https://api.github.com/repos/cilium/cilium/pulls/$pr"
  pr_json="$($GHCURL $url)"
  merge_sha="$(echo -n $pr_json | jq -r '.merge_commit_sha')"
  merged_at="$(echo -n $pr_json | jq -r '.merged_at')"

  if ((FLAGS_verbose)); then
    logecho "PR: $pr SHA: $merge_sha Merged-at: $merged_at"
  fi

  if [[ "$merge_sha" = "null" ]]; then
    if ((FLAGS_verbose)); then
      logecho "  No merge SHA"
    fi
    return
  fi

  if [[ "$merged_at" = "null" ]]; then
    if ((FLAGS_verbose)); then
      logecho "  Never merged"
    fi
    return
  fi

  if ! commit_in_release $merge_sha "$range"; then
    if ((FLAGS_verbose)); then
      logecho "  Not in release ($range)"
    fi
    return
  fi

  extract_pr_title "$pr" >> $PR_NOTES
}

###############################################################################
# Scan PRs for release-note-* labels and generate markdown for the actual
# release notes section of the report
# Uses global LAST_RELEASE CURRENT_BRANCH
generate_notes () {
  local branch_head
  local range
  local start_tag
  local release_tag
  local labels
  local body
  local tempcss=/tmp/$PROG-ca.$$
  local tempfile=/tmp/$PROG-file-1.$$
  local anchor
  local -a normal_prs
  local -a action_prs
  local -a notes_normal
  local -a notes_action
  local -a prs

  branch_head=$(git rev-parse refs/remotes/origin/$CURRENT_BRANCH 2>/dev/null)

  # If ${LAST_RELEASE[$CURRENT_BRANCH]} is unset attempt to get the last
  # release from the parent branch and then master
  : ${LAST_RELEASE[$CURRENT_BRANCH]:=${LAST_RELEASE[${CURRENT_BRANCH%.*}]}}
  : ${LAST_RELEASE[$CURRENT_BRANCH]:=${LAST_RELEASE[master]}}

  # Default
  release_tag="${POSITIONAL_ARGV[0]}"
  range="${POSITIONAL_ARGV[1]}"

  [[ "$range" =~ (.*)\.\.(.*) ]] &&
    start_tag=${BASH_REMATCH[1]}

  if [[ -z "$start_tag" ]]; then
    common::exit 1 "Unable to set beginning of range automatically." \
                   "Specify on the command-line. Exiting..."
  fi

  #range="$start_tag..$release_tag"
  logecho "Release tag range: $range"

  # If range is unterminated, finish it with $branch_head
  #[[ $range =~ \.\.$ ]] && range+=$branch_head

  # Validate range
  if ! git rev-parse $range &>/dev/null; then
    logecho
    logecho "Invalid tags/range $range !"
    return 1
  fi

  logecho

  logecho "Scanning for all merged PRs in the repository requiring release notes on the $CURRENT_BRANCH branch..."
  major_prs=($(get_prs "release-note/major"))
  echo "Major PRs: ${#major_prs[@]}"

  minor_prs=($(get_prs "release-note/minor"))
  echo "Minor PRs: ${#minor_prs[@]}"

  bug_prs=($(get_prs "release-note/bug"))
  echo "Bugfix PRs: ${#bug_prs[@]}"

  logecho
  logecho "Generating release notes..."

  if [[ ${#major_prs[@]} > 0 ]]; then
    echo "Major Changes:" >> $PR_NOTES
    for pr in "${major_prs[@]}"; do
      generate_release_note_for_pr $pr
    done
  fi

  if [[ ${#bug_prs[@]} > 0 ]]; then
    echo >> $PR_NOTES
    echo "Bugfixes Changes:" >> $PR_NOTES
    for pr in "${bug_prs[@]}"; do
      generate_release_note_for_pr $pr
    done
  fi

  if [[ ${#minor_prs[@]} > 0 ]]; then
    echo >> $PR_NOTES
    echo "Other Changes:" >> $PR_NOTES
    for pr in "${minor_prs[@]}"; do
      generate_release_note_for_pr $pr
    done
  fi

  echo >> $PR_NOTES

  logecho "Preparing layout..."
  create_body ${FLAGS_release_tars:-""} $start_tag ${release_tag:-HEAD} \
   > $RELEASE_NOTES_MD

  if ((FLAGS_htmlize_md)) && [[ ! $release_tag =~ ${VER_REGEX[dotzero]} ]]; then
    # Make users and PRs linkable
    # Also, expand anchors (needed for email announce())
    sed -i -e "s,#\([0-9]\{5\,\}\),[#\1]($CILIUM_GITHUB_URL/pull/\1),g" \
        -e "s,\(#v[0-9]\{3\}-\),$CILIUM_GITHUB_URL/blob/master/$changelog_file\1,g" \
        -e "s,@\([a-zA-Z0-9-]*\),[@\1](https://github.com/\1),g" \
     $RELEASE_NOTES_MD
  fi

  if [[ -n "$RELEASE_NOTES_HTML" ]]; then
    echo "<style type=text/css>" \
         "table,th,tr,td {border: 1px solid gray;" \
         "border-collapse: collapse;padding: 5px;}" \
         "</style>" > $tempcss

    pandoc -H $tempcss --from markdown_github --to html \
     $RELEASE_NOTES_MD > $RELEASE_NOTES_HTML

    # Remove temp file
    logrun rm -f $tempcss
  fi
}

##############################################################################
# CONSTANTS
##############################################################################
CURRENT_BRANCH=${FLAGS_branch:-$(gitlib::current_branch)} \
 || common::exit 1

PR_NOTES=/tmp/$PROG-$CURRENT_BRANCH-prnotes
# Initialize new PR_NOTES for session
>$PR_NOTES
RELEASE_NOTES_MD=$(common::absolute_path \
                   ${FLAGS_markdown_file:-/tmp/$PROG-$CURRENT_BRANCH.md})
RELEASE_NOTES_HTML=$(common::absolute_path $FLAGS_html_file)
ANNOUNCEMENT_TEXT=/tmp/$PROG-announcement

###############################################################################
# MAIN
###############################################################################
# Initialize and save up to 10 (rotated logs)
MYLOG=/tmp/$PROG.log
common::logfileinit $MYLOG 10

# BEGIN script
common::timestamp begin

# Check token
gitlib::github_api_token

# Check for packages
common::check_packages jq pandoc

# Build LAST_RELEASE dictionary
gitlib::last_releases

generate_notes || common::exit 1

common::timestamp end
