# yamllint disable rule:line-length
name: Weekly CI trigger
on:  # yamllint disable-line rule:truthy
  workflow_dispatch:
  schedule:
    - cron: '0 17 * * 6'
env:
  BRANCH_NAME: "weekly-ci"
  COMMIT_MESSAGE: "This PR is to trigger periodic CI testing"
  BODY_MESSAGE: "This PR is for the purpose of triggering periodic CI testing. We don't currently have a way to trigger CI without a PR, so this PR serves that purpose."
  COMMENT: "[citest]"
jobs:
  weekly_ci:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Create and push empty commit
        run: |
          set -euxo pipefail

          get_main_branch() {
              local br
              br=$(git branch --list main)
              if [ -n "$br" ]; then
                  echo main
                  return 0
              fi
              br=$(git branch --list master)
              if [ -n "$br" ]; then
                  echo master
                  return 0
              fi
              echo UNKNOWN
              return 1
          }

          git config --global user.name "github-actions[bot]"
          git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git checkout ${{ env.BRANCH_NAME }} || git checkout -b ${{ env.BRANCH_NAME }}
          git rebase $(get_main_branch)
          git commit --allow-empty -m "${{ env.COMMIT_MESSAGE }}"
          git push -f --set-upstream origin ${{ env.BRANCH_NAME }}

      - name: Create and comment pull request
        uses: actions/github-script@v6
        with:
          github-token: ${{ secrets.GH_PUSH_TOKEN }}
          script: |
            const head = [context.repo.owner, ":", "${{ env.BRANCH_NAME }}"].join("");
            const response = await github.rest.pulls.list({
              owner: context.repo.owner,
              repo: context.repo.repo,
              head: head,
              base: context.ref,
              state: "open"
            });
            if (response.data.length === 0) {
              const response = await github.rest.pulls.create({
                owner: context.repo.owner,
                repo: context.repo.repo,
                title: "${{ env.COMMIT_MESSAGE }}",
                body: "${{ env.BODY_MESSAGE }}",
                head: "${{ env.BRANCH_NAME }}",
                base: context.ref,
                draft: true
              });
              var pr_number = response.data.number;
            } else {
              var pr_number = response.data[0].number;
            }
            github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: pr_number,
              body: "${{ env.COMMENT }}",
            });
