# Copyright the Hyperledger Fabric contributors. All rights reserved.
#
# SPDX-License-Identifier: Apache-2.0

on:
  issue_comment:
    types: [created]
name: Automatically Trigger Azure Pipeline
jobs:
  trigger:
    name: TriggerAZP
    if: github.event.issue.pull_request != '' && contains(github.event.comment.body, '/ci-run')
    runs-on: ubuntu-latest
    steps:
    - name: Trigger Build
      run: |
        author=$(jq -r ".issue.user.login" "${GITHUB_EVENT_PATH}")
        commenter=$(jq -r ".comment.user.login" "${GITHUB_EVENT_PATH}")
        org=$(jq -r ".repository.owner.login" "${GITHUB_EVENT_PATH}")
        pr_number=$(jq -r ".issue.number" "${GITHUB_EVENT_PATH}")
        project=$(jq -r ".repository.name" "${GITHUB_EVENT_PATH}")
        repo=$(jq -r ".repository.full_name" "${GITHUB_EVENT_PATH}")

        comment_url="https://api.github.com/repos/${repo}/issues/${pr_number}/comments"
        pr_url="https://api.github.com/repos/${repo}/pulls/${pr_number}"

        pr_resp=$(curl "${pr_url}")
        isReviewer=$(echo "${pr_resp}" | jq -r .requested_reviewers | jq -c ".[] | select(.login | contains(\"${commenter}\"))" | wc -l)

        if [[ "${commenter}" = "${author}" ]] || [[ "${isReviewer}" -ne 0 ]]; then
          sha=$(echo "${pr_resp}" | jq -r ".head.sha")

          az extension add --name azure-devops
          echo ${AZP_TOKEN} | az devops login --organization "https://dev.azure.com/${org}"

          runs=$(az pipelines build list --project ${project} | jq -c ".[] | select(.sourceVersion | contains(\"${sha}\"))" | jq -r .status | grep -v completed | wc -l)
          if [[ $runs -eq 0 ]]; then
            az pipelines build queue --branch refs/pull/${pr_number}/merge --commit-id ${sha} --project ${project} --definition-name Pull-Request
            curl -s -H "Authorization: token ${GITHUB_TOKEN}" -X POST -d '{"body": "AZP build triggered!"}' "${comment_url}"
          else
            curl -s -H "Authorization: token ${GITHUB_TOKEN}" -X POST -d '{"body": "AZP build already running!"}' "${comment_url}"
          fi
        else
          curl -s -H "Authorization: token ${GITHUB_TOKEN}" -X POST -d '{"body": "You are not authorized to trigger builds for this pull request!"}' "${comment_url}"
        fi
      env:
        AZP_TOKEN: ${{ secrets.AZP_TOKEN }}
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
