#!/usr/bin/env bash
read -r -d '\n' USAGE <<EOF
Script to import pull requests from github to your local repository and to give you
some suggestion how to send them to your gerrit server.

Usage: $0 [-h] [-v] [-f] [-a]
        -f   import PRs with **failed** CI tests
        -a   import **all** PRs regardless of CI status

Example use:
cd ~/KorAP/Kustvakt
$0
EOF

ORG="KorAP"
REPO=$(basename $(git rev-parse --show-toplevel))

if [ -z "$GITHUB_KORAP_REPO_AUTH" ]; then
  cat <<EOF

If you experience limited API access, create a personal github access token:
https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token
Then set GITHUB_KORAP_REPO_AUTH="-u <user>:<access token>", for example:
export GITHUB_KORAP_REPO_AUTH="-u janedoe:53bd435ed3e456548ec2d1a94172591cc0ae1167"

EOF
fi
GET_CI_STATUS_SUCCESS="true"
GET_ALL_PRS="false"
REVIEW_SUGGESTION="+1"
while getopts ":vfah" opt; do
  case ${opt} in
  f )
    GET_CI_STATUS_SUCCESS="false"
    REVIEW_SUGGESTION="-2"
    ;;
  a )
    GET_ALL_PRS="true"
    REVIEW_SUGGESTION="+0"
    ;;
  v )
    set -x
    VERBOSE=1
    ;;
  h )
    echo "$USAGE"
    exit
    ;;
  \? )
    echo "$USAGE"
    exit
    ;;
  esac
done

WORKFLOW=$(curl $GITHUB_KORAP_REPO_AUTH -s "https://api.github.com/repos/${ORG}/${REPO}/actions/workflows" | jq '.workflows[0].id')
if [ -z $(git remote get-url github 2> /dev/null) ]; then
  git remote add github https://github.com/$ORG/$REPO
fi
git fetch github
git fetch origin
OLDHEAD=$(git log --pretty=format:%H -1)
COMMIT_MSG_HOOK_BAK_EXT=.bak.${RANDOM}
COMMIT_MSG_HOOK_BAK=.git/hooks/commit-msg${COMMIT_MSG_HOOK_BAK_EXT}
if grep --q -- '^[ ]*--trailer' .git/hooks/commit-msg; then
  sed -i${COMMIT_MSG_HOOK_BAK} -e 's/^\( *\)--trailer/\1--no-divider --trailer/' .git/hooks/commit-msg
fi
while IFS=',' read -r success nr sha message; do
  if [ "$success" == "$GET_CI_STATUS_SUCCESS" ]; then
    if git cherry-pick "$sha" > /dev/null 2> /dev/null; then
      # add closes #<nr> to let github automatically close the PR and add change-id via hook
     GIT_EDITOR="echo 'Closes #${nr}' >> $1" git commit --amend
    else
      git cherry-pick --skip
    fi
  else
    if [ "$GET_CI_STATUS_SUCCESS" == "true" ]; then
      echo "Skipping because of **failed** CI test: $nr - $message $sha"
    else
      echo "Skipping because of **sucessfull** CI test: $nr - $message $sha"
    fi
  fi
done <<<$(
  if [ "$GET_ALL_PRS" == "true" ] || [ ! -e .github/workflows ]; then
    curl $GITHUB_KORAP_REPO_AUTH -s "https://api.github.com/repos/${ORG}/${REPO}/pulls?state=open" |
     jq '.[] | { success: "true", pr:.number, sha:.head.sha, message:.title} | join(",")' |
      sed 's/[\"]//g' | sed 's/\\\\n\\\\n.*//g'
  else
    curl $GITHUB_KORAP_REPO_AUTH -s "https://api.github.com/repos/${ORG}/${REPO}/actions/workflows/${WORKFLOW}/runs?event=pull_request" |
    jq '.workflow_runs[] | select(.head_commit.message!="trigger github actions") | {success: (.conclusion=="success"), pr:.pull_requests[].number, sha:.pull_requests[].head.sha, message:.head_commit.message} | join(",")' |
    sed 's/[\"]//g' | sed 's/\\\\n\\\\n.*//g'
  fi
)
if [ -e ${COMMIT_MSG_HOOK_BAK} ]; then
  mv ${COMMIT_MSG_HOOK_BAK} .git/hooks/commit-msg
fi

NEWHEAD=$(git log --pretty=format:%H -1)
if [ "$NEWHEAD" == "$OLDHEAD" ]; then
  echo
  echo "No new pull requests"
else
  echo
  echo "New pull requests:"
  git log --graph --pretty=reference "$OLDHEAD"..HEAD
  cat <<EOF

# Copy and paste for code review:
#
# git push origin HEAD:refs/for/master
#
# ssh -p 29418 $USER@korap gerrit review --code-review $REVIEW_SUGGESTION \$(git rev-list $OLDHEAD..HEAD)

EOF
fi
