name: Build Offline K3s Installer

on:
  push:
    paths:
      - 'scripts/resolve_k3s_versions.sh'
      - 'scripts/make_k3s_offline_package.sh'
      - '.github/workflows/offline-package-k3s-installer.yaml'
  workflow_dispatch:
    
env:
  NERDCTL_VERSION: "2.1.4"

jobs:
  build-k3s-installer:
    strategy:
      matrix:
        arch: [amd64, arm64]
    runs-on: ubuntu-latest
    outputs:
      k3s_version: ${{ steps.resolve.outputs.version }}

    steps:
      - name: Checkout repo
        uses: actions/checkout@v4

      - name: Prepare toolchain (curl/jq/tar/tree + nerdctl)
        run: |
          set -euo pipefail
          sudo apt-get update
          sudo apt-get install -y curl jq tar tree

          NURL="https://github.com/containerd/nerdctl/releases/download/v${NERDCTL_VERSION}/nerdctl-${NERDCTL_VERSION}-linux-amd64.tar.gz"
          TGZ="/tmp/nerdctl-${NERDCTL_VERSION}.tgz"
          echo "Downloading: ${NURL}"
          curl -fSL --retry 3 --retry-connrefused --connect-timeout 15 "${NURL}" -o "${TGZ}"
          # 可选校验：如需严格校验，取消下面两行的注释
          # curl -fSL "${NURL}.sha256" -o "${TGZ}.sha256"
          # (cd /tmp && sha256sum -c "$(basename ${TGZ}).sha256") || { echo "SHA256 mismatch"; exit 1; }

          sudo tar -C /usr/local/bin -xzf "${TGZ}"
          sudo chmod +x /usr/local/bin/nerdctl
          sudo nerdctl --version

      - name: Resolve latest k3s version
        id: resolve
        run: |
          set -euo pipefail
          bash scripts/resolve_k3s_versions.sh

      - name: Build offline package
        env:
          K3S_VERSION: ${{ steps.resolve.outputs.version }}
          ARCH: ${{ matrix.arch }}
        run: |
            set -euo pipefail
            chmod +x scripts/make_k3s_offline_package.sh
            ./scripts/make_k3s_offline_package.sh

      - name: Validate airgap image tar
        run: |
          set -euo pipefail
          TAR="k3s-offline-package/images/k3s-airgap-images-${{ matrix.arch }}.tar"
          tmp=$(mktemp -d)
          tar -xf "$TAR" -C "$tmp" manifest.json
          configs=$(jq -r '.[].Config' "$tmp/manifest.json")
          for cfg in $configs; do
            tar -xf "$TAR" -C "$tmp" "$cfg"
            arch=$(jq -r '.architecture' "$tmp/$cfg")
            if [ "$arch" != "${{ matrix.arch }}" ]; then
              echo "unexpected arch $arch in $cfg" >&2
              exit 1
            fi
          done
          rm -rf "$tmp"

      - name: Pack final installer
        run: |
          set -euo pipefail
          # 假设脚本产出目录为 k3s-offline-package
          test -d k3s-offline-package
          tar czf offline-package-k3s-installer-${{ matrix.arch }}.tar.gz k3s-offline-package
          ls -lh offline-package-k3s-installer-${{ matrix.arch }}.tar.gz

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: offline-package-k3s-installer-${{ matrix.arch }}
          path: offline-package-k3s-installer-${{ matrix.arch }}.tar.gz
          if-no-files-found: error

  test-k3s-installer:
    needs: build-k3s-installer
    strategy:
      matrix:
        arch: [amd64, arm64]
    runs-on: ubuntu-latest

    steps:
      - name: Download Artifact
        uses: actions/download-artifact@v4
        with:
          name: offline-package-k3s-installer-${{ matrix.arch }}
          path: ./test-dir

      - name: Extract Package
        run: |
          cd test-dir
          tar -xzvf offline-package-k3s-installer-${{ matrix.arch }}.tar.gz

      - name: Install jq
        run: |
          sudo apt-get update
          sudo apt-get install -y jq

      - name: Verify k3s binary arch
        run: |
          set -euo pipefail
          BIN="test-dir/k3s-offline-package/bin/k3s-${{ matrix.arch }}"
          file "$BIN"
          if [ "${{ matrix.arch }}" = "amd64" ]; then
            file "$BIN" | grep -q 'x86-64'
          else
            file "$BIN" | grep -q 'aarch64'
          fi

      - name: Verify image platforms
        run: |
          set -euo pipefail
          TAR="test-dir/k3s-offline-package/images/k3s-airgap-images-${{ matrix.arch }}.tar"
          tmp=$(mktemp -d)
          tar -xf "$TAR" -C "$tmp" manifest.json
          configs=$(jq -r '.[].Config' "$tmp/manifest.json")
          for cfg in $configs; do
            tar -xf "$TAR" -C "$tmp" "$cfg"
            arch=$(jq -r '.architecture' "$tmp/$cfg")
            if [ "$arch" != "${{ matrix.arch }}" ]; then
              echo "unexpected arch $arch in $cfg" >&2
              exit 1
            fi
          done

      - name: Setup K3s and Test
        if: matrix.arch == 'amd64'
        run: |
          cd test-dir/k3s-offline-package
          bash install-server.sh
          KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl get nodes
          KUBECONFIG=/etc/rancher/k3s/k3s.yaml kubectl get pods -A

  publish-release:
    needs: test-k3s-installer
    runs-on: ubuntu-latest
    env:
      TAG_NAME: ${{ github.event.inputs.tag != '' && github.event.inputs.tag || format('offline-k3s-{0}', github.run_number) }}
      RSYNC_SSH_KEY: ${{ secrets.RSYNC_SSH_KEY }}
      RSYNC_SSH_USER: ${{ secrets.RSYNC_SSH_USER }}
      VPS_HOST: ${{ secrets.VPS_HOST }}
      REMOTE_ROOT: /data/update-server/nginx-ingress

    steps:
      - uses: actions/checkout@v4

      - name: Create GitHub Release
        id: create_release
        uses: actions/create-release@v1
        with:
          tag_name: ${{ env.TAG_NAME }}
          release_name: Daily Build ${{ env.TAG_NAME }}
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Download amd64 Artifact
        uses: actions/download-artifact@v4
        with:
          name: offline-package-k3s-installer-amd64
          path: release-artifacts

      - name: Download arm64 Artifact
        uses: actions/download-artifact@v4
        with:
          name: offline-package-k3s-installer-arm64
          path: release-artifacts

      - name: Upload to GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ env.TAG_NAME }}
          files: |
            release-artifacts/offline-package-k3s-installer-amd64.tar.gz
            release-artifacts/offline-package-k3s-installer-arm64.tar.gz
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Prune old releases (keep last 3)
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          set -euo pipefail
          releases=$(gh release list --limit 100 --json tagName,createdAt --jq 'sort_by(.createdAt) | reverse | .[3:] | .[].tagName')
          if [[ -n "$releases" ]]; then
            for tag in $releases; do
              gh release delete "$tag" -y
            done
          fi
