# CI: lint → typecheck → audit gate → build → scan → SBOM → image → digest-bump PR.
# Runs on a self-hosted act_runner (dedicated unprivileged user on the bastion;
# host mode, has node 22 + buildah + git). Registered against git.bztmon.com.
#
# Required repo secrets (set at go-live):
#   REGISTRY_USER / REGISTRY_TOKEN  - push to git.bztmon.com/jwright/bztmon-site (package:write)
#   HOME_OPS_SSH_KEY                - deploy key, write to home-ops ONLY
#   GITEA_TOKEN                     - open a PR on the private instance
name: build-and-deploy

on:
  push:
    branches: [main]
    paths:
      - "src/**"
      - "public/**"
      - "astro.config.mjs"
      - "package.json"
      - "package-lock.json"
      - "Dockerfile"
      - "nginx/**"
  workflow_dispatch: {}

jobs:
  build:
    runs-on: self-hosted
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install (from lockfile)
        run: npm ci

      - name: Type-check
        run: npm run check

      - name: Dependency audit gate (high/critical)
        run: npx audit-ci --config .audit-ci.json

      - name: Build
        run: npm run build

      - name: Security scan (dist)
        run: npm run scan

      - name: SBOM (CycloneDX)
        run: npx @cyclonedx/cyclonedx-npm --output-file sbom.json

      - name: Upload SBOM
        # Gitea's artifact backend doesn't support upload-artifact@v4 (GHES) — use v3,
        # and never let a best-effort artifact upload block the deploy.
        continue-on-error: true
        uses: actions/upload-artifact@v3
        with:
          name: sbom
          path: sbom.json

      - name: Registry login
        run: echo "${{ secrets.REGISTRY_TOKEN }}" | buildah login -u "${{ secrets.REGISTRY_USER }}" --password-stdin git.bztmon.com

      - name: Build & push image
        run: scripts/build-image.sh push

      - name: Push digest-bump branch to home-ops
        env:
          HOME_OPS_SSH_KEY: ${{ secrets.HOME_OPS_SSH_KEY }}
          # Optional: set secrets.HOMEOPS_PR_TOKEN to auto-open the PR. Unset = push branch only
          # (you open+merge the PR — the approval gate). NOT GITEA_TOKEN (Gitea auto-injects that).
          HOMEOPS_PR_TOKEN: ${{ secrets.HOMEOPS_PR_TOKEN }}
        run: scripts/bump-digest.sh
