{
  config,
  pkgs,
  lib,
  ...
}: let
  inherit (lib.modules) mkIf;
  cfg = config.wsl;
in {
  config = mkIf cfg.enable {
    system.build.tarballBuilderExt = pkgs.writeShellApplication {
      name = "nixos-wsl-tarball-builder-ext";

      runtimeInputs = with pkgs; [
        coreutils
        gnutar
        zstd
        nixos-install-tools
        config.nix.package
      ];

      text = ''
        if ! [ $EUID -eq 0 ]; then
          echo "This script must be run as root!"
          exit 1
        fi

        out=''${1:-nixos-wsl.tar.zst}

        root=$(mktemp -p "''${TMPDIR:-/tmp}" -d nixos-wsl-tarball.XXXXXXXXXX)
        # FIXME: fails in CI for some reason, but we don't really care because it's CI
        trap 'rm -rf "$root" || true' INT TERM EXIT

        chmod o+rx "$root"

        echo "[NixOS-WSL] Installing..."
        nixos-install \
          --root "$root" \
          --no-root-passwd \
          --system ${config.system.build.toplevel} \
          --substituters ""

        echo "[NixOS-WSL] Compressing..."
        tar -C "$root" \
          -cz \
          --sort=name \
          --mtime='@1' \
          --owner=0 \
          --group=0 \
          --numeric-owner \
          . \
          > "$out"
      '';
    };
  };
}