name: Build WSL Package

# Bakes a single WSL2 rootfs that already contains Ubuntu 22.04 + Docker Engine
# + the cicy-code image (pre-loaded into /var/lib/docker), so a Windows install
# is just: wsl --import <this> → dockerd auto-starts → docker run. No apt, no
# image pull/load on the customer machine. Uploaded to our Cloudflare R2 bucket.

on:
  workflow_dispatch:
    inputs:
      image:
        description: cicy-code image to embed
        default: cicybot/cicy-code:latest
      r2_key:
        description: R2 object key
        default: rootfs/cicy-wsl-latest.tar.gz

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      # First — actions/checkout cleans the workspace, so it has to run before
      # anything writes build artifacts into it. Needed for scripts/r2.mjs
      # (this job used to fetch a standalone ossutil binary and never checked
      # the repo out at all).
      - name: Checkout
        uses: actions/checkout@v4

      - name: Build base rootfs image (Ubuntu + Docker + autostart)
        run: |
          mkdir -p ctx
          # dockerd auto-start on WSL boot: legacy iptables (WSL2 needs it) + detached dockerd.
          cat > ctx/start-dockerd.sh <<'EOS'
          #!/bin/sh
          update-alternatives --set iptables /usr/sbin/iptables-legacy 2>/dev/null || true
          update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy 2>/dev/null || true
          pgrep dockerd >/dev/null 2>&1 || nohup dockerd >/var/log/dockerd.log 2>&1 &
          EOS
          cat > ctx/wsl.conf <<'EOS'
          [boot]
          command = /usr/local/sbin/start-dockerd.sh
          [user]
          default = root
          [automount]
          enabled = true
          options = "metadata"
          EOS
          cat > ctx/Dockerfile <<'EOF'
          FROM ubuntu:22.04
          ENV DEBIAN_FRONTEND=noninteractive
          # The GHA runner is overseas — use the default Ubuntu archive (fast here).
          # The end-user's WSL apt mirror is a separate concern (handled at runtime).
          RUN apt-get update \
            && apt-get install -y --no-install-recommends docker.io ca-certificates iptables iproute2 \
            && apt-get clean && rm -rf /var/lib/apt/lists/*
          RUN update-alternatives --set iptables /usr/sbin/iptables-legacy || true; \
              update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy || true
          COPY start-dockerd.sh /usr/local/sbin/start-dockerd.sh
          COPY wsl.conf /etc/wsl.conf
          RUN chmod +x /usr/local/sbin/start-dockerd.sh
          EOF
          docker build -t cicy-wsl-base ctx

      - name: Build WSL rootfs (Ubuntu + Docker, image NOT baked)
        run: |
          # image NO LONGER baked into the rootfs. wsl-docker.bootstrap downloads +
          # docker-loads cicy-code-latest.tar.gz at setup (像 mac/colima 那样) → WSL 也拿最新
          # 烤制镜像,且镜像更新不必重下整个 rootfs(rootfs=Ubuntu+Docker 很少变,瘦了 ~169MB)。
          docker pull "${{ inputs.image }}"
          # Still save the image so the SAME run republishes the macOS tarball (next step).
          docker save "${{ inputs.image }}" -o /tmp/cicy-image.tar
          # Run the base privileged, start an inner dockerd ONCE then stop — purely to clear
          # stale daemon runtime files so the FIRST dockerd in WSL2 starts clean. No image load.
          cid=$(docker run -d --privileged cicy-wsl-base \
            bash -c '
              nohup dockerd >/var/log/dind.log 2>&1 &
              for i in $(seq 1 60); do docker info >/dev/null 2>&1 && break; sleep 1; done
              pkill dockerd || true
              sleep 4
              # Drop stale daemon runtime files so the FIRST dockerd in WSL2 does
              # not refuse with "pid file found" (引擎没起来 root cause).
              rm -f /var/run/docker.pid /run/docker.pid /var/run/docker.sock /run/docker.sock
            ')
          docker logs -f "$cid" || true
          rc=$(docker wait "$cid"); echo "inner exit=$rc"
          # Export the container filesystem = the WSL rootfs (Ubuntu + Docker, no image).
          docker export "$cid" | gzip > cicy-wsl.tar.gz
          ls -lh cicy-wsl.tar.gz

      - name: Upload to Cloudflare R2
        env:
          R2_ACCOUNT_ID: ${{ secrets.R2_ACCOUNT_ID }}
          R2_API_TOKEN:  ${{ secrets.R2_API_TOKEN }}
        run: |
          set -e
          node scripts/r2.mjs put "${{ inputs.r2_key }}" cicy-wsl.tar.gz

      # macOS (colima) loads the cicy-code image tarball directly, NOT a WSL rootfs. So the
      # SAME run also republishes images/cicy-code-latest.tar.gz from the image already saved
      # at /tmp/cicy-image.tar — one workflow keeps BOTH platforms' docker images current
      # (this key had no producer, which is why macOS was stuck on a stale image).
      - name: Publish cicy-code image tarball to R2 (macOS / colima)
        env:
          R2_ACCOUNT_ID: ${{ secrets.R2_ACCOUNT_ID }}
          R2_API_TOKEN:  ${{ secrets.R2_API_TOKEN }}
        run: |
          set -e
          gzip -c /tmp/cicy-image.tar > cicy-code-latest.tar.gz
          ls -lh cicy-code-latest.tar.gz
          node scripts/r2.mjs put images/cicy-code-latest.tar.gz cicy-code-latest.tar.gz

      - name: Upload artifact (backup)
        uses: actions/upload-artifact@v4
        with:
          name: cicy-wsl-package
          path: cicy-wsl.tar.gz
          retention-days: 7
