name: Build Base Image (Stages 0-2)

on:
  schedule:
    # Weekly on Sunday at 04:00 UTC
    - cron: '0 4 * * 0'
  workflow_dispatch:

permissions:
  contents: write

jobs:
  build-base:
    runs-on: ubuntu-24.04-arm64
    timeout-minutes: 120
    steps:
      - uses: actions/checkout@v4

      - name: Set up pi-gen
        run: |
          git clone --depth 1 https://github.com/RPi-Distro/pi-gen.git /tmp/pi-gen-builder

      - name: Configure base-only build
        run: |
          cd /tmp/pi-gen-builder

          # Copy our config but override STAGE_LIST to only build base stages
          cp "${GITHUB_WORKSPACE}/pi-gen/config" config
          sed -i 's/^STAGE_LIST=.*/STAGE_LIST="stage0 stage1 stage2"/' config

          # Mark stage2 for export so we get the rootfs
          touch stage2/EXPORT_IMAGE

      - name: Build base image
        run: |
          cd /tmp/pi-gen-builder
          PIGEN_DOCKER_MODE=1 ./build-docker.sh

      - name: Package base rootfs
        run: |
          cd /tmp/pi-gen-builder
          DATE="$(date -u +%Y%m%d)"

          # Find the stage2 rootfs in the work directory
          ROOTFS_DIR=$(find work/ -path "*/stage2/rootfs" -type d | head -1)
          if [ -z "$ROOTFS_DIR" ]; then
            echo "ERROR: stage2 rootfs not found"
            exit 1
          fi

          echo "Packaging rootfs from: $ROOTFS_DIR"
          tar -czf "${GITHUB_WORKSPACE}/base-image-trixie-arm64-${DATE}.tar.gz" \
            -C "$(dirname "$ROOTFS_DIR")" rootfs/

          ls -lh "${GITHUB_WORKSPACE}/base-image-trixie-arm64-${DATE}.tar.gz"

      - name: Create base image release
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          DATE="$(date -u +%Y%m%d)"
          TAG="base-v${DATE}"
          TARBALL="base-image-trixie-arm64-${DATE}.tar.gz"

          # Delete previous base release if exists (keep only latest)
          gh release delete "$TAG" --yes 2>/dev/null || true
          git push --delete origin "$TAG" 2>/dev/null || true

          # Create new release
          gh release create "$TAG" "$TARBALL" \
            --title "Base Image ${DATE}" \
            --notes "Pre-baked base image (stages 0-2) for Debian Trixie arm64.

          Use with: BASE_IMAGE=./${TARBALL} ./build-image.sh full

          Built: $(date -u +%Y-%m-%d\ %H:%M:%S\ UTC)" \
            --prerelease
