name: Build and Publish Docker Image

on:
  push:
    tags:
      - 'v*.*.*'
  workflow_dispatch:
    inputs:
      manual_version:
        description: 'Manual version override (leave empty to use git tag)'
        required: false
        default: ''

env:
  # Use github.repository as the default image name
  IMAGE_NAME: ${{ github.repository }}
  REGISTRY: ghcr.io

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    # Set the permissions needed for the GitHub token to push to GHCR
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Needed to get all tags for versioning

      # Set version information
      - name: Set Version
        id: version
        run: |
          if [[ "${{ github.event.inputs.manual_version }}" != "" ]]; then
            echo "VERSION=${{ github.event.inputs.manual_version }}" >> $GITHUB_ENV
          elif [[ "${{ github.ref }}" == refs/tags/* ]]; then
            VERSION=${GITHUB_REF#refs/tags/}
            echo "VERSION=$VERSION" >> $GITHUB_ENV
          else
            VERSION=$(git describe --tags --abbrev=0 2>/dev/null || echo "dev")-$(git rev-parse --short HEAD)
            echo "VERSION=$VERSION" >> $GITHUB_ENV
          fi
          echo "BUILD_TIME=$(date -u +'%Y-%m-%d_%H:%M:%S')" >> $GITHUB_ENV
          echo "COMMIT=$(git rev-parse --short HEAD)" >> $GITHUB_ENV

      # Set up Docker Buildx for efficient builds
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      # Login to GitHub Container Registry
      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      # Extract metadata for Docker image
      - name: Extract Docker metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=ref,event=branch
            type=ref,event=pr
            type=sha,format=long
            type=raw,value=latest,enable={{is_default_branch}}

      # Build and push Docker image
      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          push: ${{ github.event_name != 'pull_request' }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          build-args: |
            VERSION=${{ env.VERSION }}
            BUILD_TIME=${{ env.BUILD_TIME }}
            COMMIT=${{ env.COMMIT }}
            UID=1000
            GID=1000
          cache-from: type=gha
          cache-to: type=gha,mode=max 