name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

jobs:
  sast:
    name: SAST (gosec)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v5
        with:
          go-version-file: go.mod
          cache: true

      - name: Run gosec
        run: make gosec

  sca:
    name: SCA (govulncheck + pnpm audit)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v5
        with:
          go-version-file: go.mod
          cache: true

      - uses: pnpm/action-setup@v4

      - name: Run govulncheck
        run: make vulncheck

      - name: Run pnpm audit
        run: make pnpm-audit

  release:
    name: Release
    runs-on: macos-latest # macOS so codesign is available for ad-hoc signing
    needs: [sast, sca]
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - uses: actions/setup-go@v6
        with:
          go-version: "1.26.4"
          cache: true

      - uses: pnpm/action-setup@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'pnpm'
          cache-dependency-path: web/pnpm-lock.yaml

      - name: Build frontend (embeds into binary)
        run: make web

      - name: Install syft (SBOMs)
        run: |
          curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b /usr/local/bin

      - uses: goreleaser/goreleaser-action@v7
        with:
          version: "~> v2"
          args: release --clean
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          # PAT with `repo` scope on Icehunter/homebrew-tap.
          # If unset, the brews publisher will fail; configure before
          # cutting a release that should land in the tap.
          # PAT with `repo` scope on Icehunter/scoop-bucket.
          # PAT with `repo` scope and a fork of microsoft/winget-pkgs
          # at Icehunter/winget-pkgs.
          RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}

  deploy-frontend:
    name: Deploy Frontend to Cloudflare Pages
    runs-on: ubuntu-latest
    needs: release
    permissions:
      contents: read
      deployments: write

    steps:
      - uses: actions/checkout@v4

      - uses: pnpm/action-setup@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '22'
          cache: 'pnpm'
          cache-dependency-path: web/pnpm-lock.yaml

      - run: pnpm install --frozen-lockfile
        working-directory: web

      - run: pnpm run build
        working-directory: web
        env:
          VITE_CLERK_PUBLISHABLE_KEY: ${{ secrets.VITE_CLERK_PUBLISHABLE_KEY }}
          VITE_CDN_BASE_URL: ${{ vars.VITE_CDN_BASE_URL }}

      - uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          command: pages deploy dist --project-name=dune-admin
          workingDirectory: web
