name: Build and Push Docker Image

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:

env:
  GHCR_IMAGE: ghcr.io/${{ github.repository }}
  DOCKERHUB_IMAGE: decolua/9router

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - uses: actions/checkout@v4

      - uses: docker/setup-buildx-action@v3

      - name: Log in to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

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

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: |
            ${{ env.GHCR_IMAGE }}
            ${{ env.DOCKERHUB_IMAGE }}
          tags: |
            type=semver,pattern={{version}}
            type=raw,value=latest,enable={{is_default_branch}}

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=registry,ref=${{ env.GHCR_IMAGE }}:buildcache
          cache-to: type=registry,ref=${{ env.GHCR_IMAGE }}:buildcache,mode=max
          platforms: linux/amd64,linux/arm64
          provenance: false
          sbom: false
