name: Build and Push Container Image

on:
  push:
    branches:
      - main
    tags:
      - "v*"
  workflow_dispatch:
    inputs:
      tag:
        description: "Git tag to build (e.g. v9.1.1)"
        required: true
      add_latest:
        description: "Also tag this image as latest"
        type: boolean
        default: false

permissions:
  contents: read
  packages: write

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

jobs:
  build-and-push:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v5
        with:
          fetch-depth: 0 # needed to fetch tags

      - name: Determine tag
        id: tag
        run: |
          if [ "${{ github.event_name }}" = "push" ]; then
            if [[ "${GITHUB_REF}" == refs/tags/* ]]; then
              # Tagged release: publish the version tag and move latest.
              echo "tag=${GITHUB_REF_NAME}" >> $GITHUB_OUTPUT
              echo "push_latest=true" >> $GITHUB_OUTPUT
            else
              # Push to main: publish a rolling edge tag plus an immutable sha tag.
              echo "tag=edge" >> $GITHUB_OUTPUT
              echo "sha_tag=sha-$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
              echo "push_latest=false" >> $GITHUB_OUTPUT
            fi
          else
            echo "tag=${{ inputs.tag }}" >> $GITHUB_OUTPUT
            echo "push_latest=${{ inputs.add_latest }}" >> $GITHUB_OUTPUT
            git checkout "refs/tags/${{ inputs.tag }}"
          fi

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

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

      - name: Build and push image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: Dockerfile
          push: true
          tags: |
            ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.tag.outputs.tag }}
            ${{ steps.tag.outputs.sha_tag != '' && format('{0}/{1}:{2}', env.REGISTRY, env.IMAGE_NAME, steps.tag.outputs.sha_tag) || '' }}
            ${{ steps.tag.outputs.push_latest == 'true' && format('{0}/{1}:latest', env.REGISTRY, env.IMAGE_NAME) || '' }}
