name: Docker Build and Push

on:
  push:
    branches:
      - main
      - classical
      - dev
      - new_knowledge
    tags:
      - 'v*'
  workflow_dispatch:

jobs:
  build-and-push:
    runs-on: ubuntu-latest
    env:
      DOCKERHUB_USER: ${{ secrets.DOCKERHUB_USERNAME }}
      DATE_TAG: $(date -u +'%Y-%m-%dT%H-%M-%S')
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Clone maim_message
        run: git clone https://github.com/MaiM-with-u/maim_message maim_message

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

      - name: Login to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Determine Image Tags
        id: tags
        run: |
          if [[ "${{ github.ref }}" == refs/tags/* ]]; then
            echo "tags=${{ secrets.DOCKERHUB_USERNAME }}/maimbot:${{ github.ref_name }},${{ secrets.DOCKERHUB_USERNAME }}/maimbot:latest" >> $GITHUB_OUTPUT
          elif [ "${{ github.ref }}" == "refs/heads/main" ]; then
            echo "tags=${{ secrets.DOCKERHUB_USERNAME }}/maimbot:main,${{ secrets.DOCKERHUB_USERNAME }}/maimbot:main-$(date -u +'%Y%m%d%H%M%S')" >> $GITHUB_OUTPUT
          elif [ "${{ github.ref }}" == "refs/heads/classical" ]; then
            echo "tags=${{ secrets.DOCKERHUB_USERNAME }}/maimbot:classical,${{ secrets.DOCKERHUB_USERNAME }}/maimbot:classical-$(date -u +'%Y%m%d%H%M%S')" >> $GITHUB_OUTPUT
          elif [ "${{ github.ref }}" == "refs/heads/dev" ]; then
            echo "tags=${{ secrets.DOCKERHUB_USERNAME }}/maimbot:dev,${{ secrets.DOCKERHUB_USERNAME }}/maimbot:dev-$(date -u +'%Y%m%d%H%M%S')" >> $GITHUB_OUTPUT
          elif [ "${{ github.ref }}" == "refs/heads/new_knowledge" ]; then 
            echo "tags=${{ secrets.DOCKERHUB_USERNAME }}/maimbot:knowledge,${{ secrets.DOCKERHUB_USERNAME }}/maimbot:knowledge-$(date -u +'%Y%m%d%H%M%S')" >> $GITHUB_OUTPUT
          fi

      - name: Build and Push Docker Image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          platforms: linux/amd64,linux/arm64
          tags: ${{ steps.tags.outputs.tags }}
          push: true
          cache-from: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/maimbot:buildcache
          cache-to: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/maimbot:buildcache,mode=max
          labels: |
            org.opencontainers.image.created=${{ steps.tags.outputs.date_tag }}
            org.opencontainers.image.revision=${{ github.sha }}