name: "Update pinned clan-core for checks"
on:
  repository_dispatch:
  workflow_dispatch:
  schedule:
    - cron: "51 2 * * *"
jobs:
  update-pinned-clan-core:
    runs-on: nix
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: true
      - name: Update clan-core for checks
        run: nix run .#update-clan-core-for-checks
      - name: Create pull request
        env:
          CI_BOT_TOKEN: ${{ secrets.CI_BOT_TOKEN }}
        run: |
          export GIT_AUTHOR_NAME=clan-bot GIT_AUTHOR_EMAIL=clan-bot@clan.lol GIT_COMMITTER_NAME=clan-bot GIT_COMMITTER_EMAIL=clan-bot@clan.lol
          git commit -am "Update pinned clan-core for checks"
          git push origin +HEAD:update-clan-core-for-checks
          set -x
          resp=$(nix run --inputs-from . nixpkgs#curl -- -X POST \
            -H "Authorization: token $CI_BOT_TOKEN" \
            -H "Content-Type: application/json" \
            -d '{
              "head": "update-clan-core-for-checks",
              "base": "main",
              "title": "Update Clan Core for Checks",
              "body": "This PR updates the pinned clan-core flake input that is used for checks."
            }' \
           "https://git.clan.lol/api/v1/repos/clan/clan-core/pulls")
          pr_number=$(echo "$resp" | jq -r '.number')

          # Merge when succeed
          while true; do
            resp=$(nix run --inputs-from . nixpkgs#curl -- -X POST \
              -H "Authorization: token $CI_BOT_TOKEN" \
              -H "Content-Type: application/json" \
              -d '{
                "Do": "merge",
                "merge_when_checks_succeed": true,
                "delete_branch_after_merge": true
              }' \
              "https://git.clan.lol/api/v1/repos/clan/clan-core/pulls/$pr_number/merge")
            msg=$(echo $resp | jq -r '.message')
            if [[ "$msg" != "Please try again later" ]]; then
              break
            fi
            echo "Retrying in 2 seconds..."
            sleep 2
          done
