name: DockerHub Nightly Build

on:
  schedule:
    - cron: "0 0 * * *"
  workflow_dispatch:

env:
  IMAGE_NAME: ${{ secrets.DOCKERHUB_USERNAME }}/ultrarag
  IMAGE_TAG: v0.3.0
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"

jobs:
  check-recent-commits:
    runs-on: ubuntu-latest
    outputs:
      should_build: ${{ steps.commit-check.outputs.should_build }}
    steps:
      - name: Checkout
        uses: actions/checkout@v5
        with:
          fetch-depth: 1

      - name: Check commits in last 24 hours
        id: commit-check
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            echo "Manual trigger detected, continue building."
            echo "should_build=true" >> "$GITHUB_OUTPUT"
            exit 0
          fi

          latest_commit_ts="$(git log -1 --format=%ct)"
          now_ts="$(date +%s)"
          age_seconds="$((now_ts - latest_commit_ts))"

          if [ "$age_seconds" -le 86400 ]; then
            echo "Recent commit detected in last 24h, continue building."
            echo "should_build=true" >> "$GITHUB_OUTPUT"
          else
            echo "No new commit in last 24h, skip docker build."
            echo "should_build=false" >> "$GITHUB_OUTPUT"
          fi

  build-and-push:
    needs: check-recent-commits
    if: needs.check-recent-commits.outputs.should_build == 'true'
    runs-on: ubuntu-latest
    permissions:
      contents: read
    strategy:
      fail-fast: false
      matrix:
        include:
          - dockerfile: Dockerfile.base-cpu
            tag_suffix: -base-cpu
          - dockerfile: Dockerfile.base-gpu
            tag_suffix: -base-gpu
          - dockerfile: Dockerfile
            tag_suffix: ""
    steps:
      - name: Checkout
        uses: actions/checkout@v5
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
      - name: Set up Buildx
        uses: docker/setup-buildx-action@v3
      - name: Login to DockerHub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          file: ${{ matrix.dockerfile }}
          push: true
          pull: true
          tags: ${{ env.IMAGE_NAME }}:${{ env.IMAGE_TAG }}${{ matrix.tag_suffix }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
