---
# yamllint disable rule:line-length
name: Weekly CI trigger
on:  # yamllint disable-line rule:truthy
  workflow_dispatch:
  schedule:
    - cron: 0 11 * * 6
env:
  BRANCH_NAME: weekly-ci
  COMMIT_MESSAGE: "ci: 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]"
permissions:
  contents: read
jobs:
  weekly_ci:
    runs-on: ubuntu-latest
    permissions:
      issues: write
      pull-requests: write
      contents: write
    steps:
      - name: Update pip, git
        run: |
          set -euxo pipefail
          sudo apt update
          sudo apt install -y git

      - name: Checkout latest code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
      - name: Create or rebase commit, add dump_packages callback
        run: |
          set -euxo pipefail

          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 main
          if [ ! -d tests/callback_plugins ]; then
            mkdir -p tests/callback_plugins
          fi
          curl -L -s -o tests/callback_plugins/dump_packages.py https://raw.githubusercontent.com/linux-system-roles/auto-maintenance/main/callback_plugins/dump_packages.py
          git add tests/callback_plugins
          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@v8
        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"
            });
            let pr_number = '';
            if (response.data.length === 0) {
              pr_number = (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
              })).data.number;
            } else {
              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 }}",
            });
