name: Base Image Build

on:
  push:
    branches: [ main, dev ]
    paths:
      - 'docker/DispatcharrBase'
      - '.github/workflows/base-image.yml'
      - 'requirements.txt'
  pull_request:
    branches: [ main, dev ]
    paths:
      - 'docker/DispatcharrBase'
      - '.github/workflows/base-image.yml'
      - 'requirements.txt'
  workflow_dispatch:  # Allow manual triggering

permissions:
  contents: write    # For managing releases and pushing tags
  packages: write    # For publishing to GitHub Container Registry

jobs:
  build-base-image:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

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

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

      - name: Generate timestamp for build
        id: timestamp
        run: |
          TIMESTAMP=$(date -u +'%Y%m%d%H%M%S')
          echo "timestamp=${TIMESTAMP}" >> $GITHUB_OUTPUT

      - name: Set repository and image metadata
        id: meta
        run: |
          # Get lowercase repository owner
          REPO_OWNER=$(echo "${{ github.repository_owner }}" | tr '[:upper:]' '[:lower:]')
          echo "repo_owner=${REPO_OWNER}" >> $GITHUB_OUTPUT

          # Get repository name
          REPO_NAME=$(echo "${{ github.repository }}" | cut -d '/' -f 2 | tr '[:upper:]' '[:lower:]')
          echo "repo_name=${REPO_NAME}" >> $GITHUB_OUTPUT

          # Determine branch name
          if [[ "${{ github.ref }}" == "refs/heads/main" ]]; then
            echo "branch_tag=base" >> $GITHUB_OUTPUT
          elif [[ "${{ github.ref }}" == "refs/heads/dev" ]]; then
            echo "branch_tag=base-dev" >> $GITHUB_OUTPUT
          else
            # For other branches, use the branch name
            BRANCH=$(echo "${{ github.ref }}" | sed 's/refs\/heads\///' | sed 's/[^a-zA-Z0-9]/-/g')
            echo "branch_tag=base-${BRANCH}" >> $GITHUB_OUTPUT
          fi

      - name: Build and push Docker base image
        uses: docker/build-push-action@v4
        with:
          context: .
          file: ./docker/DispatcharrBase
          push: true
          platforms: linux/amd64,linux/arm64
          tags: |
            ghcr.io/${{ steps.meta.outputs.repo_owner }}/${{ steps.meta.outputs.repo_name }}:base
            ghcr.io/${{ steps.meta.outputs.repo_owner }}/${{ steps.meta.outputs.repo_name }}:base-${{ steps.timestamp.outputs.timestamp }}
