name: Dependency Audit

on:
  schedule:
    - cron: '0 6 * * 1'   # Mondays 06:00 UTC
  workflow_dispatch: {}

jobs:
  audit:
    runs-on: ubuntu-latest
    env:
      DOTNET_ROOT: /home/mika/.dotnet
      GITEA_API: https://git.kuns.dev/api/v1
      REPO: releases/ClaudeDo
      ISSUE_TITLE: 'Dependency audit: vulnerable packages detected'
    steps:
      - name: Checkout main
        env:
          TOKEN: ${{ secrets.GITEA_TOKEN }}
        run: |
          set -euo pipefail
          git clone --depth 1 --branch main \
            "https://oauth2:${TOKEN}@git.kuns.dev/${REPO}.git" src

      - name: Scan for vulnerable / outdated packages
        run: |
          set -euo pipefail
          export PATH="$DOTNET_ROOT:$PATH"
          cd src

          : > audit.log
          : > vuln.md
          found=0

          # .slnx tooling needs .NET 9; iterate per-project to stay on .NET 8.
          while IFS= read -r proj; do
            echo "==== $proj ====" | tee -a audit.log
            dotnet restore "$proj" >/dev/null

            vuln="$(dotnet list "$proj" package --vulnerable --include-transitive 2>&1)"
            echo "$vuln" | tee -a audit.log
            if echo "$vuln" | grep -qi "has the following vulnerable"; then
              found=1
              {
                printf '#### `%s`\n\n```\n' "$proj"
                echo "$vuln"
                printf '```\n\n'
              } >> vuln.md
            fi

            # Outdated is informational only — never fails the run.
            dotnet list "$proj" package --outdated 2>&1 | tee -a audit.log || true
            echo "" | tee -a audit.log
          done < <(find . -name '*.csproj' | sort)

          if [ "$found" -ne 0 ]; then
            echo "::error::Vulnerable packages detected — see log above." >&2
            exit 1
          fi
          echo "No vulnerable packages found."

      - name: Report vulnerabilities to a Gitea issue
        if: failure()
        env:
          TOKEN:  ${{ secrets.GITEA_TOKEN }}
          RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
        run: |
          set -euo pipefail
          cd src

          if [ -s vuln.md ]; then
            DETAILS="$(cat vuln.md)"
          else
            DETAILS="The audit job failed before producing findings — check the run log."
          fi
          BODY="$(printf 'Automated weekly dependency audit found vulnerable packages.\n\n%s\n\n[View workflow run](%s)' \
            "$DETAILS" "$RUN_URL")"

          # Reuse an existing open issue if one is already tracking this.
          EXISTING="$(curl -sS \
            -H "Authorization: token ${TOKEN}" \
            "${GITEA_API}/repos/${REPO}/issues?state=open&type=issues&limit=50" \
            | jq -r --arg t "$ISSUE_TITLE" '.[] | select(.title==$t) | .number' | head -n1)"

          if [ -n "$EXISTING" ]; then
            echo "Commenting on existing issue #$EXISTING"
            jq -n --arg body "$BODY" '{body:$body}' \
              | curl -sS --fail-with-body -X POST \
                  -H "Authorization: token ${TOKEN}" \
                  -H "Content-Type: application/json" \
                  -d @- \
                  "${GITEA_API}/repos/${REPO}/issues/${EXISTING}/comments" >/dev/null
          else
            echo "Creating new issue"
            jq -n --arg title "$ISSUE_TITLE" --arg body "$BODY" '{title:$title, body:$body}' \
              | curl -sS --fail-with-body -X POST \
                  -H "Authorization: token ${TOKEN}" \
                  -H "Content-Type: application/json" \
                  -d @- \
                  "${GITEA_API}/repos/${REPO}/issues" >/dev/null
          fi
