name: Container Image Releaser

on:
  push:
    tags:
      - "v[0-9]+.[0-9]+.[0-9]+"
    branches:
      - "main"

concurrency: ci-container-release

permissions:
  contents: read

env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}

jobs:
  build:
    timeout-minutes: 30
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
      id-token: write

    steps:
    - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
      with:
        submodules: true
        fetch-depth: 0

    - name: Registry Login
      uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4
      with:
        registry: ${{ env.REGISTRY }}
        username: ${{ github.actor }}
        password: ${{ secrets.GITHUB_TOKEN }}

    - name: Setup QEMU
      uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4

    - name: Setup Docker Buildx
      uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4

    - name: Build and Push Container Image
      run: |
        # Get the tag if this was a tag push event
        if [[ "${{ github.ref_type }}" == "tag" ]]; then
          TAG=${{ github.ref_name }}
          # Validate tag format (must be vX.Y.Z)
          if [[ $TAG =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            # Build and push with both version tag and latest
            docker buildx build --push --platform linux/amd64,linux/arm64 \
              -t $REGISTRY/$IMAGE_NAME:$TAG \
              -t $REGISTRY/$IMAGE_NAME:latest \
              .
          else
            echo "Invalid tag format. Must be in format vX.Y.Z (e.g. v1.2.3)"
            exit 1
          fi
        else
          # For non-tag pushes, just use latest tag
          docker buildx build --push --platform linux/amd64,linux/arm64 \
            -t $REGISTRY/$IMAGE_NAME:latest \
            .
        fi


