name: Release Docker

on:
  push:
    tags:
      - "[0-9]*"
  workflow_dispatch:
    inputs:
      tag:
        description: "Image tag (e.g. 2026.06.1). Defaults to latest commit SHA."
        required: false

jobs:
  docker:
    runs-on: docker-builder
    steps:
      - uses: actions/checkout@v4

      - name: Resolve image tag
        id: meta
        run: |
          SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-7)
          echo "short_sha=$SHORT_SHA" >> "$GITHUB_OUTPUT"
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            TAG="${{ github.event.inputs.tag }}"
            if [ -z "$TAG" ]; then
              TAG="${{ github.sha }}"
            fi
          else
            TAG="${{ github.ref_name }}"
          fi
          echo "tag=$TAG" >> "$GITHUB_OUTPUT"

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          platforms: linux/amd64,linux/arm64
          sbom: true
          provenance: mode=max
          tags: |
            lerkolabs/uptop:${{ steps.meta.outputs.tag }}
            lerkolabs/uptop:latest
            lerkolabs/uptop:sha-${{ steps.meta.outputs.short_sha }}
          build-args: |
            VERSION=${{ steps.meta.outputs.tag }}
            COMMIT=${{ github.sha }}
            BUILD_DATE=${{ github.event.head_commit.timestamp }}

      - name: Scan image for CVEs
        run: |
          curl -sSfL https://raw.githubusercontent.com/anchore/grype/main/install.sh | sh -s -- -b /usr/local/bin
          grype lerkolabs/uptop:${{ steps.meta.outputs.tag }} --fail-on critical --output table || echo "::warning::CVE scan found critical issues — review output above"

      - name: Update Docker Hub description
        uses: peter-evans/dockerhub-description@v4
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
          repository: lerkolabs/uptop

      - name: Cleanup Docker artifacts
        if: always()
        run: |
          docker image prune -f
          docker builder prune -f --keep-storage=2GB
