name: Build and push telegraf-snmp-unifi image
run-name: ${{ gitea.actor }} is building and pushing telegraf-snmp-unifi image
on:
  push:
    branches:
      - main
      - 'feat/**'
    paths:
      - 'telegraf-snmp-unifi/**'
      - '.gitea/workflows/telegraf-snmp-unifi.yaml'
    tags:
      - 'v*'
  workflow_dispatch:

env:
  RESULT_IMAGE_NAME: tools/telegraf-snmp-unifi

jobs:
  build-and-push-image:
    runs-on: docker
    steps:
      - name: Checkout
        uses: actions/checkout@v5

      - name: Log in to registry
        uses: docker/login-action@v3
        with:
          registry: ${{ vars.PRIVATE_REGISTRY_DOMAIN }}
          username: ${{ vars.PRIVATE_REGISTRY_USER }}
          password: ${{ secrets.PRIVATE_REGISTRY_PASSWORD }}

      - name: Install private CA certificate
        run: |
          echo "${{ vars.PRIVATE_REGISTRY_CA_CERT }}" | sudo tee /usr/local/share/ca-certificates/private-ca.crt > /dev/null
          sudo update-ca-certificates

      - name: Compute image tags
        id: tags
        run: |
          BASE="${{ vars.PRIVATE_REGISTRY_DOMAIN }}/${{ env.RESULT_IMAGE_NAME }}"
          {
            echo "value<<EOF"
            echo "${BASE}:${{ gitea.sha }}"
            if [ "${{ gitea.ref_name }}" = "main" ]; then
              echo "${BASE}:latest"
            fi
            if [[ "${{ gitea.ref }}" == refs/tags/v* ]]; then
              echo "${BASE}:${{ gitea.ref_name }}"
            fi
            echo "EOF"
          } >> "$GITHUB_OUTPUT"

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

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
        with:
          config-inline: |
            [registry."harbor.lan"]
              ca = ["/usr/local/share/ca-certificates/private-ca.crt"]

      - name: Build and push image
        uses: docker/build-push-action@v6
        with:
          context: telegraf-snmp-unifi
          platforms: linux/amd64,linux/arm64
          push: true
          tags: ${{ steps.tags.outputs.value }}
