name: Build and Publish Docker Image

# Trigger the workflow on push to the main branch or on manual dispatch
on:
  push:
    branches:
      - main
  workflow_dispatch:
  schedule:
    - cron: '0 0 * * 0'  # Runs at midnight UTC every Sunday

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

    steps:
      # 1. Checkout the repository
      - name: Checkout repository
        uses: actions/checkout@v3

      # 2. Set up QEMU and Docker Buildx (for multi-platform builds, optional)
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

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

      # 3. Log in to Docker Hub
      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: hykilpikonna
          password: ${{ secrets.DOCKERHUB_TOKEN }}
          
      # 3. Log in to GitHub Container Registry (ghcr.io)
      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          # Use GITHUB_TOKEN for authentication
          password: ${{ secrets.GITHUB_TOKEN }}

      # 4. Cache Docker layers to speed up builds (optional but recommended)
      - name: Cache Docker layers
        uses: actions/cache@v3
        with:
          path: /tmp/.buildx-cache
          key: ${{ runner.os }}-buildx-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-buildx-

      # 5. Build and push the Docker image
      - name: Build and push Docker image
        uses: docker/build-push-action@v4
        with:
          context: .
          push: true
          tags: |
            hykilpikonna/aquadx:latest
          platforms: linux/amd64,linux/arm64
          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,dest=/tmp/.buildx-cache
