# Nightly drift detection: diffs local configuration against Azure and
# opens/updates an issue when they diverge. Generated by `rigg ci init`.
name: rigg drift detection

on:
  schedule:
    - cron: "17 4 * * *"
  workflow_dispatch: {}

permissions:
  id-token: write
  contents: read
  issues: write

jobs:
  drift:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install rigg
        run: cargo install rigg --locked

      - name: Azure login (OIDC)
        uses: azure/login@v2
        with:
          client-id: ${{ vars.AZURE_CLIENT_ID }}
          tenant-id: ${{ vars.AZURE_TENANT_ID }}
          subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}

      - name: Diff against {{RIGG_ENV}}
        id: diff
        continue-on-error: true
        run: |
          set +e
          rigg diff --all --env {{RIGG_ENV}} --exit-code --format markdown > drift.md
          echo "exit=$?" >> "$GITHUB_OUTPUT"

      - name: Open or update drift issue
        if: steps.diff.outputs.exit == '5'
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const body = fs.readFileSync('drift.md', 'utf8').slice(0, 65000);
            const title = 'Configuration drift detected by rigg';
            const issues = await github.rest.issues.listForRepo({
              ...context.repo, state: 'open', labels: 'rigg-drift'
            });
            if (issues.data.length > 0) {
              await github.rest.issues.update({
                ...context.repo, issue_number: issues.data[0].number, body
              });
            } else {
              await github.rest.issues.create({
                ...context.repo, title, body, labels: ['rigg-drift']
              });
            }
