name: CI

on:
  push:
    tags:
      - "v*.*.*"
  pull_request:
    paths:
      - "go.sum"
      - "go.mod"
      - "**.go"
      - ".github/workflows/ci.yml"
      - ".golangci.yml"
    branches:
      - "main"

jobs:
  tests:
    name: Tests & Linters
    runs-on: ubuntu-latest
    steps:
    - name: Set up Go
      uses: actions/setup-go@v2
      with:
        go-version: '1.21'
    - name: Check out code
      uses: actions/checkout@v2
    - name: "Run Linters"
      uses: golangci/golangci-lint-action@v3
      with:
        version: latest
        args: --verbose
    - name: Run tests
      run: go test -v ./...


  build:
    name: Build & Publish on Tag
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@master
        with:
          fetch-depth: 1

      - name: Get TAG
        id: get_tag
        run: echo TAG=${GITHUB_REF#refs/tags/} >> $GITHUB_ENV

      - name: Docker meta
        id: meta
        uses: docker/metadata-action@v4
        with:
          images: |
            st3ga/opnsense-exporter
          tags: |
            type=semver,pattern={{version}}

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v2
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Login to Docker Hub
        if: github.event_name != 'pull_request'
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Release build
        id: release_build
        uses: docker/build-push-action@v3
        with:
          platforms: linux/amd64,linux/arm/v6,linux/arm64
          build-args: |
            Version=${{ env.TAG }}
          context: .
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}