# ════════════════════════════════════════════════════════════════════════════
# NoData Protect — GitHub Actions verification workflow
#
# Drop this into .github/workflows/nodata-verify.yml in your repo.
#
# What it does:
#   1. Installs @nodatachat/protect
#   2. Verifies any *.nodatasig sidecars in the repo
#   3. Verifies the .nodata-tree.sig at the repo root if present
#   4. Fails the build if any sidecar is broken or any signed file was modified
#
# This means: a tampered file in a PR cannot reach main without the verify
# step failing. Anyone with `nodata verify` access can detect the break.
#
# Free for any project. No NoData account required for verification.
# ════════════════════════════════════════════════════════════════════════════

name: NoData verify

on:
  pull_request:
    branches: [main, master, develop]
  push:
    branches: [main, master]

jobs:
  verify:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Install @nodatachat/protect
        run: npm install -g @nodatachat/protect

      - name: Verify all sidecars
        run: |
          set -e
          fails=0
          while IFS= read -r sig; do
            file="${sig%.nodatasig}"
            echo "Verifying: $file"
            if ! nodata verify "$file" --quiet; then
              echo "::error file=$file::NoData signature verification failed"
              fails=$((fails+1))
            fi
          done < <(find . -name '*.nodatasig' -not -path './node_modules/*')
          if [ "$fails" -gt 0 ]; then
            echo "::error::$fails NoData verifications failed. Tampered or stale signatures."
            exit 1
          fi

      - name: Verify tree signature (if present)
        if: hashFiles('.nodata-tree.sig') != ''
        run: |
          nodata verify --dir . --emit-diff
          if [ $? -ne 0 ]; then
            echo "::error::Tree verification failed — files in this branch differ from .nodata-tree.sig manifest"
            exit 1
          fi

      - name: Annotate PR with verify summary
        if: github.event_name == 'pull_request' && always()
        run: |
          echo "## NoData verification" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          if [ "${{ job.status }}" = "success" ]; then
            echo "OK — all signatures match." >> $GITHUB_STEP_SUMMARY
          else
            echo "FAIL — at least one signed file was modified or its sidecar broken." >> $GITHUB_STEP_SUMMARY
            echo "" >> $GITHUB_STEP_SUMMARY
            echo "Run \`nodata verify <file>\` locally to see which files diverged." >> $GITHUB_STEP_SUMMARY
          fi
