name: DockerHub - Build & Push

on:
  push:
    tags:
      - v*

jobs:
  build:
    runs-on: ubuntu-22.04

    steps:
      - uses: actions/checkout@v4

      - name: Set up JDK 17
        uses: actions/setup-java@v4
        with:
          java-version: '17'
          distribution: 'temurin'
          cache: maven

      - name: Cache local Maven repository
        uses: actions/cache@v3
        with:
          path: ~/.m2/repository
          key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
          restore-keys: |
            ${{ runner.os }}-maven-

      - name: Build with Maven
        run: mvn -B package --file pom.xml -Dmaven.test.skip=true

      - name: Get Maven project version
        id: version
        run: |
          echo "VERSION=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)" >> "$GITHUB_OUTPUT"

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

      - name: Build and push Docker image
        env:
          DOCKER_NAMESPACE: ${{ secrets.DOCKER_NAMESPACE }}
          DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
          DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
          VERSION: ${{ steps.version.outputs.version }}
        run: |
          docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD
          cd snail-job-server/snail-job-server-starter/ \
            && docker buildx build --platform linux/amd64,linux/arm64 \
            -t ${DOCKER_NAMESPACE}/snail-job:latest \
            -t ${DOCKER_NAMESPACE}/snail-job:${VERSION} \
            --push .
