name: push-artifact-to-circle-ci
concurrency:
  group: ${{ github.workflow }}-${{ github.event.number }}-${{ github.event.ref }}
  cancel-in-progress: true
# will be changed to on workflow_run
on:
  workflow_run:
    workflows: ["docs"]
    branches-ignore: ["master"]
    types:
      - completed

jobs:
  Push-Artifact-to-CircleCI:
    if: ${{ github.event.workflow_run.conclusion == 'success' }}
    runs-on: ubuntu-latest
    defaults:
      run:
        shell: bash -l {0}
    steps:
    - name: Trigger CircleCI download and publication of HTML Doc Artifact
      env:
        EVENT_OBJ:  ${{ toJson(github.event) }}
        COMMIT_SHA:  ${{ github.event.workflow_run.head_sha }}
        REPO_NAME:  ${{ github.event.workflow_run.head_repository.full_name }}
        CIRCLECI_TOKEN: ${{ secrets.CIRCLECI_TOKEN }}
        RUN_ID: ${{github.event.workflow_run.id}}
      run: |
        echo "github.event.workflow_run.head_sha"
        echo ${{ github.event.workflow_run.head_sha }}
        echo "github.event.workflow_run.head_repository.html_url"
        echo ${{ github.event.workflow_run.head_repository.html_url }}
        echo "RUN_ID"
        echo $RUN_ID
        # Acquire the Pull Request Number from Github API
        echo "automated curl"
        PR_NUMBER=$(curl -H "Accept: application/vnd.github.groot-preview+json"   https://api.github.com/repos/$REPO_NAME/commits/$COMMIT_SHA/pulls 2>/dev/null | jq '.[0].number')
        echo "PR_NUMBER"
        echo $PR_NUMBER

        # Use Pull Request Number to trigger pipeline on CircleCI which will just download artifact,
        # unzip it and make it available for browsing
        curl --request POST \
          --url https://circleci.com/api/v2/project/gh/braindecode/braindecode/pipeline \
          --header "Circle-Token: $CIRCLECI_TOKEN" \
          --header 'content-type: application/json' \
          --header 'x-attribution-actor-id: github_actions' \
          --header 'x-attribution-login: github_actions' \
          --data \{\"branch\":\"pull/$PR_NUMBER/head\",\"parameters\":\{\"github-artifact-url\":\"https://nightly.link/braindecode/braindecode/actions/runs/$RUN_ID/HTML-Docs.zip\"\}\}
        # Just for debugging
        echo "EVENT_OBJ"
        echo $EVENT_OBJ
