name: Build container image
on:
  push:
    branches:
      - master
    tags:
      - '*'

env:
  # Force colored output (see https://bixense.com/clicolors/ and https://force-color.org/)
  TERM: xterm-256color
  CLICOLOR: 1
  CLICOLOR_FORCE: 1

jobs:
  publish-docker-image:
    if: github.repository_owner == 'gbdev'
    runs-on: ubuntu-latest
    permissions:
      packages: write
    steps:
      - name: Checkout repo
        uses: actions/checkout@v7

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v4
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push the master container image
        if: github.ref == 'refs/heads/master'
        run: |
          COMMIT_HASH=$(git rev-parse --short HEAD)
          sed -i "2i LABEL org.opencontainers.image.description=\"RGBDS container image, containing the git version master:$COMMIT_HASH\"" Dockerfile
          docker build . --tag ghcr.io/gbdev/rgbds:master
          docker push ghcr.io/gbdev/rgbds:master

      - name: Build and push the version-tagged container image
        if: startsWith(github.ref, 'refs/tags/')
        run: |
          TAG_NAME=${GITHUB_REF#refs/tags/}
          sed -i "2i LABEL org.opencontainers.image.description=\"RGBDS container image for the release version $TAG_NAME\"" Dockerfile
          docker build . --tag ghcr.io/gbdev/rgbds:$TAG_NAME
          docker tag ghcr.io/gbdev/rgbds:$TAG_NAME ghcr.io/gbdev/rgbds:latest
          docker push ghcr.io/gbdev/rgbds:$TAG_NAME
          docker push ghcr.io/gbdev/rgbds:latest

      - name: Delete untagged container images
        if: github.repository_owner == 'gbdev'
        uses: Chizkiyahu/delete-untagged-ghcr-action@v6
        with:
          # Requires a personal access token with delete:packages permissions
          token: ${{ secrets.PAT_TOKEN }}
          package_name: 'rgbds'
          untagged_only: true
          except_untagged_multiplatform: true
          owner_type: 'org'
