name: CI

on:
  workflow_dispatch:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "*" ]

jobs:
  docker:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        alpine: [ "3.17.7", "3.18.6", "3.19.1", "3.20.0" ]
        variant: [ "", "openrc" ]
        latest: [ false ]
        include:
          - alpine: "3.20.0"
            variant: ""
            latest: true
          - alpine: "3.20.0"
            variant: "openrc"
            latest: true
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - uses: actions/github-script@v7
        id: alpine-minor-version
        with:
          # The script returns 1.15 from 1.15.10
          script: return "${{ matrix.alpine }}".substr(0, "${{ matrix.alpine }}".lastIndexOf("."))
          result-encoding: string

      - name: Docker metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          labels: |
            maintainer=The Dockage Authors
          images: |
            dockage/alpine
          flavor: |
            latest=false
            suffix=${{ format(matrix.variant != '' && '-{0}' || '', matrix.variant) }}
          tags: |
            ### versioning strategy
            # dockage/alpine:3.16.2
            # dockage/alpine:3.16
            # dockage/alpine:3
            # dockage/alpine:3.16.2-openrc
            # dockage/alpine:3.16-openrc
            # dockage/alpine:3-openrc
            # dockage/alpine:latest
            type=semver,pattern={{version}},value=${{ matrix.alpine }}
            type=semver,pattern={{major}}.{{minor}},value=${{ matrix.alpine }}
            type=semver,pattern={{major}},value=${{ matrix.alpine }},enable=${{ matrix.latest }}
            type=raw,value=latest,suffix=,enable=${{ matrix.latest && matrix.variant == '' }}

      - name: Login to DockerHub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

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

      - name: Build images
        uses: docker/bake-action@v4
        with:
          push: ${{ github.ref_name == github.event.repository.default_branch }}
          targets: ${{ matrix.variant }}
          sbom: true
          files: |
            ./docker-bake.hcl
            ${{ steps.meta.outputs.bake-file }}
        env:
          CONTEXT: ${{steps.alpine-minor-version.outputs.result}}

      - name: Docker Hub Description
        uses: peter-evans/dockerhub-description@v4
        if: ${{ github.event_name == 'push' && github.ref_name == github.event.repository.default_branch }}
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
          short-description: ${{ github.event.repository.description }}